Reputation: 1423
In my model I specified a regular expression for simple password validation
[Required(ErrorMessage="Error")]
[RegularExpression("(?=.{6,})(?=.*\\d)|(?=.*\\W)", ErrorMessage= "Error")]
public string Password { get; set; }
As expected this produces an html element
<input class="textbox-regular" data-val="true" data-val-regex="Error" data-val-regex-pattern="(?=.{6,})(?=.*\d)|(?=.*\W)" data-val-required="Error" id="Password" name="Password" type="password" />
This is a valid JavaScript Regex but password never matches. Is this a limitation of JQuery validator?
Thx
Upvotes: 2
Views: 4125
Reputation: 1423
Although there are single regular expressions that will do what I wanted, I can achieve a better user experience by breaking this up into 3 validations, so that the user gets specific messages about what is needed. for example
[Required(ErrorMessage="Please enter a password")]
[StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long")]
[RegularExpression("(.*\\d.*)|(.*[@#$%^&+=\\*].*)", ErrorMessage = "Password must contain a digit or special character")]
Upvotes: 1
Reputation: 2915
What your statement consists of is three positive, look-ahead assertions. Positive, look-ahead assertions don't return what is found so I don't think you can have a truth value generated when nothing is returned. Would something like this produce what you need?
((?=.*\W)|(?=.*\d)).{6,}
Or in your string:
"((?=.*\\W)|(?=.*\\d)).{6,}"
Here I asserted that there will be at least six of something and they must contain either a non-word character or a digit. The six or more characters will be returned because I didn't place it in a positive look-ahead assertion. Because the value will only be returned when the value inside matches these assertions, the user input should pass inspection appropriately.
A valid regular expression doesn't mean that it is going to match what you expect it to match. What is it, exactly, that you are hoping to match?
My assumption is that you are hoping to match a minimum of six characters with at least one digit OR at least one non-word character?
Upvotes: 1
Reputation:
This is suprising since it should match almost everything.
Is the validator supposed to show the error message when it matches or fails?
Maybe the regex is supposed to match the whole string. If so, you can try this
"^(?:(?=.{6,})(?=.*\\d)|(?=.*\\W)).*$"
and see what happens.
Try using ^$
on an empty string, then try it on a string with length.
Upvotes: 1