zahabba
zahabba

Reputation: 3231

How to specify which condition is not matching?

I have a regex pattern that I'd like to apply to passwords:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[[:punct:]])./

There are 4 capture groups. I'd like to be able to know which of the capture groups don't match the supplied string, so I can give specific feedback to a user.

For example: abcd43 -> 1st & 3rd groups true; 2nd and 4th false (So I can customize an error: "Your password must contain at least one capital letter and a punctuation character.")

Upvotes: 1

Views: 40

Answers (3)

aghast
aghast

Reputation: 15310

Javascript does not directly support named capture groups in regular expressions. Your best bet then would be to simply check the groups, and map the numbers to a condition, perhaps through an array. So you might have 1 -> "lower case", 2 -> "upper case", etc.

Then just build a message corresponding to the failure(s), and display that message.

"lower case" -> "Passwords must contain at least one lower case letter"
"upper case" -> "Passwords must contain at least one upper case letter."

Now, with that said, PLEASE, PLEASE don't do this. I use a password generator, plus a password store, for my logins. If you're going to impose more restrictions than just length, please publish them all, right up front. Don't try to "customize" the error message to tell me what I'm missing. (And, realistically, just require a long password. If you require 16 characters with no other limits, you're more secure than 8 characters with 1 digit, 1 cap, and 1 punct.)

Upvotes: 1

Amir H. Bagheri
Amir H. Bagheri

Reputation: 1416

Just set a varibale as your match group and check for every group:

var pattern =/...../ //whatever
 var ma  = 'my string'.match(pattern);
 if (!ma)
   console.log('No match');
 else{
   console.log(ma[0]) // first group.
   console.log(m[1]); // second group;

  }

Now simply check that each group has a value or not and each index represents the corresponding parenthesis in-order:

if (!m[0]){
    alert('your password does not match first parenthesis'); 
 } 

Upvotes: 1

klutt
klutt

Reputation: 31409

The simplest way is to check the four groups separately.

You can use something as easy as:

if(!lowerCase(pass))
    print "No lower case letters"
else if(!upperCase(pass))
    print "No upper"
else if(!digits(pass))
    print "No digits"
etc...

Upvotes: 1

Related Questions