0

I have the following code for Password Validation to test different cases and add valid and invalid classes to show the correctness in my HTML file.But I have a lot of if-else blocks to verify all the conditions. I tried implementing with switch statement but not luck. Any leads on how this can be implemented with a lot of if-else conditions. Thanks!

var pwdCheck = (str) => {
  var upper = /[A-Z]/g,
    numbers = /[0-9]/g,
    lower = /[a-z]/g;
  if (str.match(upper)) {
    uppercase.classList.remove("invalid");
    uppercase.classList.add("valid");
  } else {
    uppercase.classList.remove("valid");
    uppercase.classList.add("invalid");
  }
  // Numbers //
  if (str.match(numbers)) {
    numeric.classList.remove("invalid");
    numeric.classList.add("valid");
  } else {
    numeric.classList.remove("valid");
    numeric.classList.add("invalid");
  }
}
1
  • Validation block first, store the result in a variable, then a single block that sets classes based on the result of the validation. Commented Apr 12, 2019 at 9:41

2 Answers 2

2

Why can't you use && operator to combine two different conditions to minimize if.. else ladder to single if else

var pwdCheck = (str) => {
  var upper = /[A-Z]/g,
    numbers = /[0-9]/g,
    lower = /[a-z]/g;

  //Here you can use multiple conditions to check your password. I used && to combine two conditions
  if (str.match(upper) && str.match(numbers)) {
    uppercase.classList.remove("invalid");
    uppercase.classList.add("valid");
  } else {
    uppercase.classList.remove("valid");
    uppercase.classList.add("invalid");
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can use ternary operator str.match(upper) ? true : false, that can reduce your code and improves readability and store let removeClass = uppercase.classList.remove("invalid"); as local variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.