0

I need to validate my password such that it must contain small alphabets, capital alphabets, digits and special characters. My code looks like this:

if (password.length < 8 || !/([a-zA-Z])/.test(password) || !/([0-9])/.test(password) || !/([!,%,&,@,#,$,^,*,?,_,~])/.test(password)){
     console.log('Error: password is too weak');
}

As you can see I have put up many tests in the if condition. Can I make it a single regex to achieve my purpose?

1
  • I think your regexps don't do what you want... Commented Apr 25, 2016 at 13:15

1 Answer 1

1

You could try this:

var regex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");

if (!regex.test(password)) {
    console.log('Error: password is too weak');
}

(?=.*[a-z]) checks if password contains at least 1 lowercase character

(?=.*[A-Z]) checks if password contains at least 1 uppercase character

(?=.*[0-9]) checks if password contains at least 1 numeric character

(?=.*[!@#\$%\^&\*]) checks if password contains at least 1 special character.

(?=.{8,}) checks if password contains at least 8 characters or more.

Sign up to request clarification or add additional context in comments.

3 Comments

If I have to make sure that the password can not have the characters out of above mentioned options, how do I ensure that?
What do you mean? The code I wrote is a working piece of code, just replace it with your own and test it..
I mean, I want my password to have only alphabets, digits and special characters I have listed. I also want to ensure that the user can't input any other characters in the password other than alphanumerals and special characters listed above.

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.