skip to Main Content

I’m trying to do a password validation regex, it must ask for an upper case, a lower case, a special character, a number, and to not have any white spaces, so I implemented the following RegEx:

/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[.!@#$%^&*])[^s][a-zA-Z0-9.!@#$%^&*][^s]{8,16}$/

But I need to put more than 8 characters to work for some reason.

I typed my password as: Yama#892

Which is supposed to be 8 characters but Regex didn’t accept it until I type it like this for example: Yama###892

If I’m correct those are 10 characters.

So do some characters not count towards quantifier? If not how do I count for all 8 characters?

This is how my code looks:

//...
const PASSWORD_REGEX =
  "^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[.!@#$%^&*])[^\s][a-zA-Z0-9.!@#$%^&*][^\s]{8,16}$";

if (password && !password.match(PASSWORD_REGEX)) {
    errors["password"] = "Password is invalid.";
  }
//...

2

Answers


  1. ignoring the lookaheads, it says:

    /^S[a-zA-Z0-9.!@#$%^&*]S{8,16}$/
      ^ starts with non-space
         ^ then has ONE character of the list
                             ^ then ends with 8..16 non-spaces
    

    Remove [s]-s (S is equivalent to them btw) ant it’ll work fine
    (you don’t need whitespace check (?!.*s) as you limit chars in [a-zA-Z0-9.!@#$%^&*])

    Login or Signup to reply.
  2. @Dimava‘s answer already explained why your initial Regex isn’t accepting passwords with 8 characters.

    You can find a cleaned up, working version of your code bellow:

    function isValidPassword(password) {
      const PASSWORD_REGEX = /^(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^ws])(?!.*s).{8,16}$/;
      return PASSWORD_REGEX.test(password);
    }
    
    console.log(isValidPassword("Yama#892"));
    console.log(isValidPassword("2!Short"));
    console.log(isValidPassword("Has Spaces"));
    console.log(isValidPassword("noSpecialCharacter"));
    console.log(isValidPassword("1234!tooLong!1234"));

    Improvements:

    1. Uses d for digits.
    2. Uses [^ws] non-alphanumeric character.
    3. Uses test instead of match as we don’t need to extract the password.
    4. Use Lookaheads to cover all criteria but number of characters. Once the Lookaheads are in place one can use a .{8,16} for the password length instead of having to restrict valid characters.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search