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}$
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.
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>
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