Wednesday, October 15, 2008

Username Regex Validation

While accepting values from user you must validate the values because wrong values (like XSS attacks) can cause harm to your database and website.

The validation can be done on server side and can also be done on client side.
Here I am explaining server side as this is the most secure way.
Althrough the client side validation is included in the source code

Click here to download visual studio solution code


Regex Code:

The Regular Expression below validates the username format.

^[a-zA-Z0-9_]{5,20}$

Scope:

So while creating a new user for a website you can validate the username string with the following business logic:
1) User name must be between 5 to 20 characters.
2) User name can have lowercase and uppercase characters.
3) User name can be alpha-numeric.
4) No special character allowed.

As you can see this is a very basic code to evaluate simple username for your website.

Implementation:

Asp.net HTML code:

<asp:TextBox ID=”txtRegex” runat=”server”></asp:TextBox>
<asp:Button ID=”btnValidate” runat=”server” Text=”Validate value” OnClick=”btnValidate_Click” />
<asp:Label ID=”lblResultRegex” runat=”server” Text=”"></asp:Label></div>

Asp.net Code Behind:

using System.Text.RegularExpressions;

protected void btnValidate_Click(object sender, EventArgs e)
{
if (Regex.IsMatch(txtRegex.Text, @”^[a-zA-Z0-9_]{3,16}$”) == true)
{
lblResultRegex.Text = “username ok”;
}
else
{
lblResultRegex.Text = “username invalid”;
}
}

Now just run the application an verify the results.

Click here to download visual studio solution code

1 comment:

Saravanakumar.S said...

It`s very useful for me....thank you...