Thursday, September 19, 2024

Validating Strong Passwords in C# and ASP.NET

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.

Tag:

Add to Del.icio.us | Digg | Reddit | Furl

Bookmark Murdok:

Mads Kristensen currently works as a Senior Developer at Traceworks located
in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in
2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and
web services in his daily work as well. A true .NET developer with great passion for the simple solution.

Home

Related Articles

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

Buy new construction florida home. What users dislike :.