How do you disable a button until a set of if statements are passed using Javascript?

Viewed 190

There are a series of if statements attached to an input element using an event listener; how do you disable a button until all of these conditional statements are passed?

button = document.querySelector("#submit")
button.disabled = true
passwordInput.addEventListener("keyup", e => {
    let inputValidator = e.target.value
    let numberValidator= inputValidator.match(/\d+/g)
    if (inputValidator === "") {
        errorEmpty.style.display = "block"
    } else {
        errorEmpty.style.display = "none"
    }
    if (inputValidator.length < 20) {
        errorLength.style.display = "block"
    } else {
        errorLength.style.display = "none"
    }
    if (inputValidator === inputValidator.toLowerCase()) {
        errorUppercase.style.display = "block"
    } else {
        errorUppercase.style.display = "none"
    }
    if (inputValidator === inputValidator.toUpperCase()) {
        errorLowercase.style.display = "block"
    } else {
        errorLowercase.style.display = "none"
    }
    if (numberValidator == null) {
        errorNumber.style.display = "block"
    } else {
        errorNumber.style.display = "none"
    }
})
1 Answers

I believe you can simply as follows:

Assume it's invalid until you have passed your tests. Note: you can simply the test with a single RegEx to test all numeric between 20-30 characters. This is easier to read.

If you need additional tests, simply add them inside the handler.

Simple demo:

const button = document.querySelector('#submit');
const error = document.querySelector('#error');

// assume invalid until tests pass
button.disabled = true;

passwordInput.addEventListener('keyup', (e) => {
  const currentValue = e.target.value;
  
  // only numbers, between 20 and 30 characters
  const isNumber = /^\d{20,30}$/.test(currentValue);

  if (!isNumber) {
    error.textContent = 'must be numeric, min 20 chars, max 30';
    
    return;
  }

  // if you need another test
  /*
  if (...) {
    error.textContent = 'must contain x/y etc';
    
    return;
  }
  */

  // ok
  error.textContent = '';
  button.disabled = false;
});
#error {
  color: red;
  display: block;
}
<div id="error">&nbsp;</div>
<input type="text" id='passwordInput' /><button id="submit" type="submit">Submit</button>

Related