I have this regular expression that should work for password like P@ssword1234. However it doesn't seem to be matching. I've used this same regex in Angular and it worked
This is the password criteria below
// 10 characters or more
// at least one digit
// at least one uppercase letter
// at least one lowercase letter
// at least one special character
[DisplayName("Password")]
[Required(ErrorMessage = "Please enter your password.")]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.*[!@#$%^&*(),.?"":{}|<>])(?=.*[a - z])(?=.*[A - Z])(?=.*\d)[a-zA-Z\d!@#$%^&*(),.?"":{}|<>]{10,}$",
ErrorMessage = "Password must contain at least 10 characters, including at least 1 uppercase letter, at least 1 lowercase letter, at least one number and a special character.")]
Your mistake is in writing [a - z]
instead of [a-z]
. The former actually means "the letter a
, or any characters between <space>
and <space>
, or the letter z
". In other words, only the characters a
,
and z
.
Here is the "fixed" regex:
@"^(?=.*[!@#$%^&*(),.?"":{}|<>])(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*(),.?"":{}|<>]{10,}$"
...However, as mentioned in the comment above, I'd advise against putting such an arbitrary list of "required special characters" in the password. Wouldn't it be better to define this much more loosely, e.g. "Anything that's not a letter or number qualifies as being 'special'"?
You could achieve that with something like this:
^(?=.*[^a-zA-Z0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{10,}$