New Document
ASP.NET Validation Controls

ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. If you are not familiar with Validation Controls in ASP.NET, here's a recommended read for you.

In this article, let us see some tips and tricks that can be applied to the validation controls. This article is for beginner and intermediate users who have been using validation controls. There is something for everyone!!


Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.

Tip 2: The display property for the ASP.NET validation controls has 3 settings: None, Static(default), and Dynamic. 'Static' outputs HTML code (related to error) at all times even when no error has occurred. So when there is more than one validation control placed next to the field, the first validation control occupies screen space even when there is no error. In case the second validation control fires an error message, the message is pushed away from the control since the first validation control is occupying screen space.

Set the 'display' property of a validation control to 'Dynamic'. This property renders the error message with the attribute display:none; It helps you to display the error message next to the control .

Tip 3: To prevent validation to occur on the click of the Cancel button, set the 'CausesValidation' property to false

< asp:Button ID="btnCancel" Runat="server" CausesValidation="False" Text="Cancel" />

Tip 4: Use the 'InitialValue' property of the RequiredFieldValidator to validate controls like combobox which have a default value.

For eg: If your combobox has a default item called "--Select--" and you want that the user should select a value other than the default value before submitting the form, then set the 'InitialValue' property of the RequiredFieldValidator to "--Select--".

< asp:DropDownList ID="DropDownList1" runat="server">
            < asp:ListItem Value="--Select--" />
            < asp:ListItem Value="Item1" />
            < asp:ListItem Value="Item2" />
            < asp:ListItem Value="Item3" />
        < /asp:DropDownList>
        < asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="DropDownList1" InitialValue="--Select--">< /asp:RequiredFieldValidator>

Tip 5: A RegularExpressionValidator can be used to handle string patterns. For eg: A Name textbox that should accept a maximum of 30 characters with only alphabets, space, fullstop(.) and a '(apostrophe). A regularexpression like '^([a-zA-z.'\s]{2,30})$' does the trick.

However when you are using Localization and using a language like Arabic, you have to often provide for validating characters in a different dialect. You can solve this using the following technique: - In the Resource.resx file, create a resourcekey called ValidName giving it a value of ^([a-zA-z.'\s]{2,30})$ - In the Resource.ar-EG.resx file, use the same key but with a diff value ^([\u0600-\u06FF.'\s]{2,30})$ Use it in your page using the following way. Observe the bold text:

  
< asp:RegularExpressionValidatorID='regEVFname' runat='server'ControlToValidate='txtName'
Display='Dynamic'ErrorMessage='Invalid'
ValidationExpression='< %$ Resources:Resource, ValidName %>'SetFocusOnError='True'>< /asp:RegularExpressionValidator>
 

When the user selects English, he can enter only A-Za-z. Similarly for Arabic, he can enter only the Arabic characters and not English.

Tip 6: The validation controls provide both Server and Client Side validation. To turn off client-side validation, set the 'EnableClientScript = false'

< asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server"
   Text="Error" ControlToValidate="TextBox1" EnableClientScript="false"/>

Tip 7: Use CompareValidator to validate date with format of "dd/MM/yyyy". The validator uses the CultureInfo object of the thread to determine date format. So what you need to do is to set the desired culture format in the Page directive

 < %@ Page culture="your culture" %>

This tip was shared by PeterBlum in the asp.net forums. By the way, Peter has an amazing suite of data entry and validation controls on his site at a reasonable price.

Tip 8: Instead of the textual error message, you can even add an image or sound to your validator control. The Text and Error Message property accepts HTML tags.

< asp:TextBox ID="TextBox1" runat="server">< /asp:TextBox>
        < br/>
< asp:RequiredFieldValidator ControlToValidate="TextBox1" EnableClientScript="false" ID="RequiredFieldValidator1" runat="server" Text="< bgsound src='C:\Windows\Media\Windows Error.wav'>">< /asp:RequiredFieldValidator>

Just make sure that the EnableClientScript="false" when you want a sound instead of a text message.

Tip 9: If you have two set of forms (eg: Login and Registration) in a single page and want to keep the validation of the two groups separate, use 'ValidationGroups'. All you need to do, is to specify a common group name for a set of controls that you want to validate separately.

< div>
            < asp:TextBox ID="TextBox1" ValidationGroup="Group1" runat="server">< /asp:TextBox>
            < br />
            < asp:RequiredFieldValidator ControlToValidate="TextBox1" ValidationGroup="Group1" ID="RequiredFieldValidator1" runat="server" Text="Error">< /asp:RequiredFieldValidator>
            < asp:Button ID="Button1" runat="server" ValidationGroup="Group1" Text="Button" />
        < /div>
        < br />
        < br />
        < div>
            < asp:TextBox ID="TextBox2" ValidationGroup="Group2" runat="server">< /asp:TextBox>
            < br />
            < asp:RequiredFieldValidator ControlToValidate="TextBox1" ValidationGroup="Group2" EnableClientScript="false" ID="RequiredFieldValidator2" runat="server" Text="Error">< /asp:RequiredFieldValidator>
            < asp:Button ID="Button2" runat="server" ValidationGroup="Group2" Text="Button" />
        < /div>    
	

Tip 10: Other validator controls like CompareValidator, RangeValidator etc. do not provide a way to detect if the field is blank or required. The only way is to do this is to add a RequiredFieldValidator along with the other validator controls.

However one exception being the CustomValidator which provides a property called 'ValidateEmptyText'. Just set it to true and it validates the field even if the user has kept the field blank.

Tip 11: If you want your validation error message to appear in the 'ValidationSummary' control, then set the 'ErrorMessage' property on that validation control. Also, setting 'ShowMessageBox = true' on the ValidationSummary enables you to display a popup alert.

Tip 12: In order to create a CustomValidationControl you have to derive from the 'BaseValidator' class and implement the 'EvaluateIsValid()' method.

Tip 13: In case of an error, the validation controls allow you to set focus on a control in error using the 'SetFocusOnError' property.

< asp:RequiredFieldValidator SetFocusOnError="true" ControlToValidate="TextBox1" ID="RequiredFieldValidator1" runat="server" Text="Error!!">< /asp:RequiredFieldValidator>

ASP.Net validation controls validate the user input data to ensure that useless, unauthenticated or contradictory data don.t get stored.

ASP.Net provides the following validation controls:

  1. RequiredFieldValidator

  2. RangeValidator

  3. CompareValidator

  4. RegularExpressionValidator

  5. CustomValidator

  6. ValidationSummary

The BaseValidator Class:

The validation control classes inherit from the BaseValidator class and inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls:

MembersDescription
ControlToValidateIndicates the input control to validate.
Display Indicates how the error message is shown.
EnableClientScriptIndicates whether client side validation will take.
EnabledEnables or disables the validator.
ErrorMessageError string.
Text Error text to be shown if validation fails.
IsValidIndicates whether the value of the control is valid.
SetFocusOnErrorIt indicates whether in case of an invalid control, the focus should switch to the related input control.
ValidationGroupThe logical group of multiple validators, where this control belongs.
Validate()This method revalidates the control and updates the IsValid property.
The RequiredFieldValidator:

The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box.

The syntax for the control:

<asp:RequiredFieldValidator ID="rfvcandidate" 
        runat="server" ControlToValidate ="ddlcandidate"
        ErrorMessage="Please choose a candidate" 
        InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
The RangeValidator:

The RangeValidator control verifies that the input value falls within a predetermined range.

It has three specific properties:

PropertiesDescription
Typeit defines the type of the data; the available values are: Currency, Date, Double, Integer and String
MinimumValueit specifies the minimum value of the range
MaximumValueit specifies the maximum value of the range

The syntax for the control:

<asp:RangeValidator ID="rvclass" 
       runat="server" 
       ControlToValidate="txtclass" 
       ErrorMessage="Enter your class (6 - 12)" 
       MaximumValue="12" 
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>
The CompareValidator:

The CompareValidator control compares a value in one control with a fixed value, or, a value in another control.

It has the following specific properties:

PropertiesDescription
Typeit specifies the data type
ControlToCompareit specifies the value of the input control to compare with
ValueToCompareit specifies the constant value to compare with
Operatorit specifies the comparison operator, the available values are: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual and DataTypeCheck

The basic syntax for the control:

<asp:CompareValidator ID="CompareValidator1" 
        runat="server" 
        ErrorMessage="CompareValidator">
</asp:CompareValidator>
The RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching against a pattern against a regular expression. The regular expression is set in the ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular expressions:

Character EscapesDescription
\bMatches a backspace
\t Matches a tab
\r Matches a carriage return
\vMatches a vertical tab
\fMatches a form feed
\nMatches a new line
\Escape character

Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters.

MetacharactersDescription
.Matches any character except \n
[abcd]Matches any character in the set
[^abcd]Excludes any character in the set
[2-7a-mA-M]Matches any character specified in the range
\wMatches any alphanumeric character and underscore
\WMatches any non-word character
\sMatches whitespace characters like, space, tab, new line etc.
\SMatches any non-whitespace character
\dMatches any decimal character
\DMatches any non-decimal character

Quantifiers could be added to specify number of times a character could appear

QuantifierDescription
*Zero or more matches
+One or more matches
?Zero or one matches
{N}N matches
{N,}N or more matches
{N,M}Between N and M matches

The syntax for the control:

<asp:RegularExpressionValidator ID="string"
        runat="server"
        ErrorMessage="string"
        ValidationExpression="string"
        ValidationGroup="string">
</asp:RegularExpressionValidator>
The CustomValidator:

The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation.

The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, like JavaScript or VBScript, which the browser can understand.

The server side validation routine must be called from the control.s ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net.

The basic syntax for the control

<asp:CustomValidator ID="CustomValidator1" 
       runat="server" 
       ClientValidationFunction=.cvf_func.
       ErrorMessage="CustomValidator">
</asp:CustomValidator>
The ValidationSummary Control

The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation.

The following two mutually inclusive properties list out the error message:

  • ShowSummary: shows the error messages in specified format.

  • ShowMessageBox: shows the error messages in a separate window.

The syntax for the control:

<asp:ValidationSummary ID="ValidationSummary1" 
       runat="server" 
       DisplayMode = "BulletList" 
       ShowSummary = "true"
       HeaderText="Errors:" />
Validation Groups:

Complex pages have different groups of information provided in different panels. In such a situation a need for performing validation separately for separate group, might arise. This kind of situation is handled using validation groups.

To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property.

Example:

The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. We will be using the validation controls to validate the user input.


Required Field Validator


Provides form validation.Properties:


Id="img"      Creates an unique identifier

Runat="server"        Sets the image for server side processing

ControlToValidate="FieldID"        Sets the control to be validated

Display="Dynamic/Static"        Sets the validation space used by the error message

Text="Error Message"        Sets the error message

Example: < asp:requiredfieldvalidator runat="server" ControlToValidate="CustName" Display="Dynamic" Text="Field Required" Font-Name="verdana" Font-Size="10"/>

The form in Design view:

form in Design view

The content file code:

<form id="form1" runat="server">
<table style="width: 66%;">
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg" 
           Text="President Election Form : Choose your president" 
           runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" Width="239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate" 
       runat="server" ControlToValidate ="ddlcandidate"
       ErrorMessage="Please choose a candidate" 
       InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" 
      runat="server" 
      RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" 
       runat="server" 
       ControlToValidate="rblhouse" 
       ErrorMessage="Enter your house name">
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass" 
       runat="server" ControlToValidate="txtclass" 
       ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" 
       MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" Width="250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" 
      runat="server" 
      ControlToValidate="txtemail" ErrorMessage="Enter your email" 
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click" 
style="text-align: center" Text="Submit" Width="140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" 
      runat="server" 
      DisplayMode ="BulletList" 
      ShowSummary ="true"
      HeaderText="Errors:" />
</form>

The code behind the submit button:

protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}


Previous                                                                                                                                                       Next

Back to Top