简体   繁体   中英

Password validation regex: require and forbid certain characters

I have an MVC form with jQuery validation and System.ComponentModel.DataAnnotations

Problem is if I enter & in the password textbox then jQuery and MVC Model.Isvalid allows it, even though it's not one of the allowed characters.

I have tried to search for this on Google but the results I get back have nothing to do with the issue. ie JavaScript: client-side vs. server-side validation - Stack Overflow

My regex is below in case I have made a mistake with that.

RegularExpression("^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,10})", 
  ErrorMessage = "{0} must be between 6 and 10 characters and have at least 1 upper case letter, 1 lower case letter, 1 number and contain either @#$%")

The pattern in your example ^((?=.*\\\\d)(?=.*[az])(?=.*[AZ])(?=.*[@#$%]).{6,10}) uses positive lookaheads to ensure certain character classes are present in the input string but it will not in any way prevent other types of characters to appear. Each lookahead group starts with .* which allows literally anything hence & or any other character as a matter of fact will be accepted in the input string and whatever a lookahead signifies will be enforced in addition.

In other words, this approach using only positive lookaheads will make some types of characters required but it will not make any characters disallowed .

To overcome this, you can simply add another lookahead group but this time a negative one:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?!.*[&]).{6,10}$

Also, pay attention to end the pattern with string terminator $ (which was missing in your example). Without that the regex engine will produce a match for inputs that are more than 10 characters long.

See example here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM