First, you need .*
inside your look-ahead clauses to enable those characters to be at any position in the matching string. Without that- all those characters would have to be at the start of your string.
Second, you need to actually have a capturing clause, or you'll get a null match- which will be considered invalid (Why? See below). So
(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]*
would give you the entirety of the matching password. You could check password length here as well-
(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]{8,}
Would make the password have to be greater than 8 characters in length.
As for why you need a value captured by the regex, the RegexValidationAttribute
's IsValid(object value)
method uses the following logical statement to return if the entered value is valid according to the regex. (where m
is the Match
from the given pattern on the given value, and stringValue
is the given value)
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
View the source yourself
Consider if you had the validating RegEx of .{3,8}
- meaning any string between three and eight characters in length. You attempt to validate the value 123456789
. The Regex Matches this string! 12345678
is between three and eight characters in length! Actually, so is 23456789
. And 123
, for that matter. Just checking for a match is not enough, you must further check that the whole value matches.