Validation in ASP.NET

In many cases, you may need to validate the user input before processing their form submissions. For example, on a user registration form, you may need a validation mechanism to make sure that the email address entered by the user is a valid one. Or, if there is text box where users need to enter the price of a product, you many want to make sure that the user input is composed of numbers not letters.

In ASP.NET there are 5 types of validators as described in the following table (Source: MSDN).

RequiredFieldValidator Checks that the user has entered or selected anything.
RegularExpressionValidator Checks user input against a regular expression. This allows a wide variety of checks to be made and can be used for things like ZIP codes and phone numbers.
CompareValidator Compares an input control to a fixed value or another input control. It can be used for password verification fields, for example. It is also possible to do typed date and number comparisons.
RangeValidator Much like CompareValidator, but can check that the input is between two fixed values.
CustomValidator This allows you to write your own code to take part in the validation framework.

Validating a Required Entry: RequiredFieldValidator

In almost every form in a ASP.NET web application, there will be some required fields that user cannot leave empty or not-selected. For example, in a payment form, you would not allow users to skip most of the fields such as card information and expiration date. In such scenarios you can use RequiredFieldValidator. You can add a RequiredFieldValidator control in your form and associated it with the input field that you require user to enter a value or make a selection.

Let’s create a project with one page and add a textbox control to the page:

1

Let’s drag RequiredFieldValidator from the toolbox and drop it next to the text box control. We will need to associate it with the textbox control. Also, note that we need to add a button to submit the form which will trigger the validation process. Your page should look similar to this:

2

  • ControlToValidate: This is where you provide the ID of the input control that should be validated.
  • ErrorMessage: You can determine the text of the error message if the input control is left empty or not selected.
  • Display: You can decide how the validation error message will be displayed on the page.

Please run the application and test it by leaving the text box empty:

3

Let’s use Display attribute for the validator and also add a small text after the validator control as see below:

4

Let’s test it:

5

As you may see when you test it, when we use a Static display, the space for the validator control is preserved even if there is no error message displayed by the validator. If you do not want the validator behave this way, then you will need to use Dynamic display:

<asp:RequiredFieldValidator ID="reqValid_name" runat="server" ForeColor="red" ErrorMessage="* Required"  ControlToValidate="txt_Name">
    Display="Dynamic"
</asp:RequiredFieldValidator>

Let’s test it again:

6

As you observe, the validation message is dynamically added to the page when the validation fails. Otherwise, it was discarded and not reserved a space.

How about if we have a drop down control, which by default, always have an initially selected value? For example, there might be a drop down list to let users select their state. The drop down list might have a default item, such as “–Select your state–“, which would be an invalid selection if users do not choose a state from the list. However, the RequiredFieldValidator cannot determine itself that it is an invalid selection. Hopefully, there is a way to configure RequiredFieldValidator so that it can correctly validate the selection.

We can use InitialValue property to indicate what is an invalid value Validation fails only if the value of the drop down list matches this InitialValue. Let’s add a drop down list and its associated RequiredFieldValidator:

7

Please make sure that the first item in the drop down list is “-1” and the InitialValue of the validator control is also “-1”. This will tell the validator control that “-1”, which is the value of the first item in the drop down list, is not a valid selection. Let’s test it:

8

Validating if the values match : CompareValidator

The CompareValidator is used to check if values of two input controls are the same or not, if different, the validation fails. The very common use of this validator is to check if the passwords match in a user registration form. Let’s add two textbox controls for entering password, and associate a CompareValidator control:

9

One important properties of CompareValidator is ControlToCompare where you need to provide the ID of the control against which the comparison should be performed for the validation. Here is how your page design should look like:

10

Please run your application and test it.

Validating against a range of values: Range Validator

You can use RangeValidator control when you need to make sure that the user input should fall within a specific range of values, which can be between two numbers, between two dates, between alphabetic characters. The properties that you need to use to define the range are MinimumValue and MaximumValue. You can also indicate the data type of the values that the control will validate by using Type property.

Below is an example of the use of RangeValidator control to validate if the birth year is between 1900 and 2010:

Birth year:
<asp:TextBox ID="txt_Year" runat="server"></asp:TextBox>
<asp:RangeValidator ID="rangeValYear" runat="server" ForeColor="red" Display="Dynamic" ControlToValidate="txt_Year" MaximumValue="2010" MinimumValue="1900" Type="Integer" ErrorMessage="* Invalid.">

</asp:RangeValidator>

Regular Expressions: RegularExpressionValidator

If you have very specific validation requirements, such as allowing only 5-digits for zip, or a dollar $ sign for a price entry, you may need to define a pattern against which the user entry should be examined for the validation. Regular Expressions are used to create the pattern. RegularExpressionValidator can help you to validate the user input based on the regular expression pattern provided in the ValidationExpression property. For example, the following is a textbox where user should enter email, and the associated RegularExpressionValidator control that validates if the entry is a valid email by using ^\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ pattern.

<asp:TextBox ID="txt_Email" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="regExVal_Email" runat="server" ErrorMessage="* Invalid" ForeColor="red" ControlToValidate="txt_Email" ValidationExpression="^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$">
</asp:RegularExpressionValidator>

Are you further interested in learning validation in ASP.NET Web Forms, here are some useful resources:

You need to include the following in Web.Config:


<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Leave a comment