Validate 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.
>
Comments
Comments are closed