Windows Phone Developers

Wednesday, April 14, 2010

How to validate password using C# (.NET)

How to check password using C# Regular Expressions / How to enforce strong password using C# .NET

One of the common methods to check and validate password is through regular expressions. The criteria for strong password is :

1. Password should be minimum eight characters in length
2. Password should contain atleast a digit and an alphabet
3. Password should contain a non-alphanumeric character

The code uses Regular Expressions and hence the following directive is used:

using System.Text.RegularExpressions; 

The code below checks for the length:

if (sPassword.Length < 8 )
                {
                    throw new Exception("Password should contain mimimum 8 chars");   
                }

the code below checks for presence of atleast one number
sPattern = "\\d";
                oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one numeric character");
                }

the code below checks for presence of atleast one alphabet
sPattern = "\\w";
                oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one alphabet character");
                }

the code below checks for presence of atleast one non-alphanumeric character
string sPattern;
                sPattern = "[^a-zA-Z0-9\n\r\t ]";
                Regex oReg = new Regex(sPattern, RegexOptions.IgnoreCase);
                if (oReg.IsMatch(sPassword) == false)
                {
                    throw new Exception("Password should contain mimimum one non-alphanumeric character");   
                }
Exceptions are raised and handled if the criteria is not matching Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment