I’m finally back from vacation, expect some impressions of Gran Canaria in the near future. For now, here’s a little HowTo for enforcing strong passwords.
Regex is a good way to deal with password validation. If you want your users to choose strong passwords here’s how to do it:
This regular expression will enforce a password to be at least 8 characters and to be a mix of letters and numbers. Additionally they need to have at least one uppercase letter.
^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$
“pAssword555†will be accepted.
Serverside implementation:
public static bool IsPasswordStrong(string password)
{
return Regex.IsMatch(password, @"^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$");
}
Clientside implementation:
<asp:TextBox runat="server" ID="PasswordBox" TextMode="password" />
<asp:RegularExpressionValidator runat="server"
ControlToValidate="PasswordBox"
ValidationExpression="(?=.{8,})[a-zA-Z]+[^a-zA-Z]+|[^a-zA-Z]+[a-zA-Z]+"
Display="Dynamic"
ErrorMessage="Password must be 8 chars long and has to contain letters and numbers." />
Simple and effective, enjoy!
8 comments ↓
This is exactly what I’ve been looking for minus one option. I need to also enforce a “Special Character” as well as what you already have. I’m fairly new to ASP.NET and wondered if you have any ideas or could help.
Thanks
Austins Inkspot
Just put in an additional [] into the Regex defintion containing your special character set, e.g.: [$%§]
Thanks Andreas. I actually took it a few steps further and configured a string that conforms to complex AD password configuration. I’ve included it below to share:
Well I guess your site blocks code posting. Let’s try this: (?=^.{8,255}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*
Great, good job Austins!
This doesn’t work exaclty as you describe – “pAssword555” doesn’t work, and the pattern seems to force the first input to a lowercase , followed by an uppercase followed by a number, but even this doesnt work all the time depending on what follows – its very erratic at best.
Hi,
This is really great. The requirement I have is like this
Password must contain minimum of 8 characters and satisfy 3 out of 4 rules below
1.Must contain Special characters
2.Must contain Upper case
3.Must contain Lower case
4.Must contain Numerics
Hi,
The requirement I have is like this
Password must contain minimum of 8 characters ,max of 15 characters, and satisfy 3 out of 4 rules below
1.Must contain Special characters
2.Must contain Upper case
3.Must contain Lower case
4.Must contain Numerics
Leave a Comment