The asp.net validation controls enable us to quickly validate user inputs in a variety of ways. This post talks about using RegularExpressionValidator to validate username in a registration page. Often we want to limit the types of characters which can be allowed in the username. For this example, we would only allow the following characters. a to z, A to Z, 0 to 9. By using a Regular expression validator, not only we successfully validate the user input, we can also provide immediate response to the user regarding the correctness of the username entered. So, let's delve into the code.
<asp:Textbox id="txtUsername" runat="SERVER" MaxLength="20" />
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtUsername" ValidationExpression="[a-zA-Z0-9]+" ErrorMessage="The username can only contain (a-z, A-Z, 0-9)" /<
This code snippet is a part of the registration page. Here we declare a text box for user to enter the username. Then we have a asp.net RegularExpressionValidator control which validates the control's value and shows the error message provided if the expression didn't match. The key properties of the validator are:
| ControlToValidate | This property indecates the control who's value is to be validated |
| ValidationExpression | This is the regular expression which should be used while validating |
| ErrorMessage | The error message to display in case the regular expression didn't evaluates to true |
Thoughtful use of the asp.net validation control can make the life much simpler and also provide a rich experience to the user.