Category Archives: Regex

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.

Regex Code:
The Regular Expression below validates the username format.

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: 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> 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”;
        lblResultRegex.Text = “username invalid”;

Now just run the application an verify the results.

To download a visual studio source code visit