Can anyone help me write a regular expression for checking if a password has at least one letter and one number in it?
I have a requirement that users passwords must be alphanumeric and I want to be able to check for that using a regular expression.
Can anyone help me write a regular expression for checking if a password has at least one letter and one number in it?
I have a requirement that users passwords must be alphanumeric and I want to be able to check for that using a regular expression.
bool isValid = Regex.IsMatch(password, @"[a-zA-Z]") &&
Regex.IsMatch(password, @"\d");
If you want it in one regex you can use "[a-zA-Z].*\\d|\\d.*[a-zA-Z]" though two seperate checks may be more readable.
Edit: An approach with two checks, which I find quite readable, might look like this:
Regex.IsMatch(password, "\\d") && Regex.IsMatch(password, "[a-zA-Z]")
Positive lookahead is what you're looking for. The regex looks like this:
(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+
Here, (?=.*[A-Za-z]) is the positive lookahead which asserts that your string as at least one character, and (?=.*[0-9]) asserts that it has at least one digit. It's important to note that the positive lookahead doesn't return a match, but rather asserts whether a match exists or not. So, you should read the previous regex as "assert that it has at least one character; assert it has at least one digit; now that we know the assertions have passed, just check for alphanumeric characters".
This is very interesting because it allows you to easily combine the validation requirements of your application, without making your regex very complex. For example, if you now require the string to have exactly 20 characters, you just need to add a new positive lookahead assertion, like so:
(?=[A-Za-z0-9]{20})(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]+
Hope it helps!