Dhwani
Dhwani

Reputation: 7626

.match() returns null for regular expression of password

I have written javascript code to check Minimum 4 and Maximum 8 characters at least 1 Uppercase Alphabet, 1 Lowercase Alphabet, 1 Number and 1 Special Character, but it returns null for both wrong and right string. I don't know whats issue. pls help.

var password = 'okK1@'; // you can take anything
var a;
a = password.match("^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@@$!%*?&])[A-Za-z\d$@@$!%*?&]{4,8}");
if(a == false){
  alert('false');
}
else if (a == true){
  alert('true');
}
else{
  alert('null');
}

Upvotes: 1

Views: 172

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173582

JavaScript doesn't support look-behind in regular expressions; that said, it's easier to split up the requirements:

var password = ...;

var errors = [];

if (password.length < 4 /* || password.length > 8 */) {
    errors.push("Password must be at least 4 characters");
}
if (!/[A-Z]/.test(password)) {
    errors.push("Password must contain at least one uppercase letter");
}
if (!/[a-z]/.test(password)) {
    errors.push("Password must contain at least one lowercase letter");
}
if (!/\d/.test(password)) {
    errors.push("Password must contain at least one digit");
}
if (!/[$@!%*?&]/.test(password)) {
    errors.push("Password must contain at least one special character");
}

You can choose to exit early using a return false;, but doing it in this manner will have the advantage of telling the user exactly why their password is not good.

Upvotes: 3

Related Questions