Validate strong passwords in C# and ASP.NET

Sep 17, 2006

It’s always a good idea to have a password policy when creating new applications. A password policy can vary from project to project, but the important part is just to have one to begin with. It is very difficult to implement later in the process and then change all the users’ passwords accordingly.

You can do a lot of things to enforce strong passwords, but the most versatile one is probably using regular expressions.

This regular expression will enforce a password to be at least 8 characters, and to be a mix of letters and numbers.

(?=.{8,})[a-zA-Z]+[^a-zA-Z]+|[^a-zA-Z]+[a-zA-Z]+
“hello123” will be accepted.

If you want to take it further and force at least one uppercase letter as well, this will do the trick:

^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$
“HEllo123” will be accepted.

Here are some ways to implement this in your own C# or ASP.NET project.

Server-side

Use this simple method to check if a password is strong or not. You can change the regular expression to suit your needs.

public static bool IsPasswordStrong(string password)

{

  return Regex.IsMatch(password, @"^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$");

}

>

Client-side

In ASP.NET you can use the RegularExpressionValidator control to enforce the password policy.

<asp:TextBox runat="server" ID="txtPassword" TextMode="password" />

 

<asp:RegularExpressionValidator runat="server"

ControlToValidate="txtPassword"

ValidationExpression="(?=.{8,})[a-zA-Z]+[^a-zA-Z]+|[^a-zA-Z]+[a-zA-Z]+"

Display="Dynamic"

ErrorMessage="Password must be 8 characters and have both letters and numbers." />

It does not have to be complicated to add a little extra security.

>* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (2) -

 Mike GQ
Mike GQ
9/20/2006 1:28:49 PM #

Wow, this is like the third blog post of yours that I am going to use in an app I'm developing.  The business object validation saved me about a week of coding validation controls, now this points me in the right direction as well... thanks Mads

Mads Kristensen
Mads Kristensen
9/20/2006 3:17:14 PM #

I'm glad to hear Mike.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.