Click here to Skip to main content
Click here to Skip to main content
Go to top

Exploring ASP.NET Validation Controls

, 11 Aug 2012
Rate this:
Please Sign up or sign in to vote.
Here I'm going to explore ASP.NET Validation controls in depth with samples. Validation as an Image , Icon, Sound, Multiple Validations, Conditional Validations, Validation Group, CausesValidation, Page.Validate, Validation Properties and Methods, Client Side Validation, ValidatorValidate Client Sid


Table Of Contents  


Introduction 

It's very important to validate the user input in any data entry forms. Improper validation of form data is one of the main causes of security vulnerabilities. Invalid data can cause unexpected errors in system and also It exposes your website to attacks such as cross-site scripting and SQL injections etc. ASP.NET is rich with validation controls and In this article I’m trying to explore the ASP.NET Validation controls in depth with the help of samples.  I hope you will enjoy this article.

For your reference I have attached the source code(s) for all the sections with this article. 

I have put my time and efforts on all of my articles, Please don't forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles.   

Background  

If we are assuming that the user will enter all data in expected form then it’s a wrong assumption. It’s always better to validate the user input before accepting to the system. For an example if we are expecting a number input from the user, then allow only numbers in that data entry control to avoid unexpected behavior of the system. The amount of validation you put in a program depends on how complex the system is. ASP.NET Validation controls can be used for Server-side and Client-side validations.  

We can validate the user input from client-side and or server-side, if we just wanted to validate the user input only in client-side then we can use JavaScript or any other scripting languages.  It's always advised to to do validations in server side also. 

Validation Controls in ASP.NET - Overview 

We can easily validate the user input by using ASP.NET validation controls. It provides an easy to use mechanism for all common types of standard validation. This validation controls can be used with HTML and Web Server controls. Six validation controls are available with ASP.NET as of now, they are as follows. 

The RequiredFieldValidator Control - Ensures that the user does not skip a mandatory entry field . 
 
The CompareValidator Control – Compares one controls value with another controls value, constants and data type using a comparison operator (equals, greater than, less than, and so on). 
 
The RangeValidator Control - Checks the user's input is in a given range (eg: numbers or characters). 
 
The RegularExpressionValidator Control - Checks that the user's entry matches a pattern defined by a regular expression.  
 
The CustomValidator Control - Checks the user's entry using custom-coded validation logic. 
 
The ValidationSummary Control - Displays a summary of all validation errors inline on a web page, in a message box, or both. 

All validation controls except ValidationSummary are used to validate the user input, whereas the ValidationSummary control is just used to display the entire validation error messages in a particular area. This error list can be printed in the browser and or displayed as a dialogue box. The CustomValidator allows you to implement your own validations. By using CustomValidator you can perform complex validations or you can validate the data from the database etc.

I have explained all the Validation Controls in the section - Validation Controls in depth.  

Read More…  

If you look at the hierarchy you can see that there is one another validation control derived from BaseValidator class.  

The Dynamic Validator Control - The DynamicValidator control is part of the ASP.NET Dynamic Data framework. The control catches exceptions that are thrown from the data model during validation and raises the exception as a validation event on the Web page.     

This control can be found in the Dynamic Data section of the Toolbox .

 

This control was added in .NET Framework 3.5 SP1 release. The DynamicValidator control can be used with data fields or data entities. It catches exceptions that are thrown in LINQ-to-SQL classes or entity in extensibility methods in the data model. The DynamicValidator control is associated with the controls that accept user input.  

By default, ASP.NET Dynamic Data does not display all exceptions from the data model in the page, because some database exceptions might contain confidential information. Dynamic Data displays ValidationException values only. If you want your application to display other exceptions, you can create a DynamicValidator control, provide the exceptions that you want to display, and attach the exceptions to the DynamicValidator control. The exceptions that are thrown in the data model will be displayed in all pages in the application.  

Which Controls Can be Validated  

All controls that can be validated have a ValidationPropertyAttribute attribute , which indicates which property should be read for the purposes of validation. For validation to work client-side as well, this property must correspond to the value attribute of the HTML element that gets rendered on the client Also, a control must have a single logical value on the client. This is why RadioButtonList can be validated, but CheckBoxList cannot. 

If you are creating a validatable UserControl then the System.Web.UI.ValidationPropertyAttribute attribute must be applied to that control, example. 

[ValidationPropertyAttribute("Message")]
public class MessageControl : Label
{
   private int _message = 0;
   public int Message
   {
      get 
      {
         return _message;
      }
      set
      {
         _message = value;
      }
   }
} 
Read More... 

Inheritance Hierarchy  

All validation controls except ValidationSummary are derived from BaseValidator class and share some properties.   

If you look at the above image you can see that CompareValidator and RangeValidator are derived from the BaseCompareValidator class. This class offers two main common property in addition to those offered by BaseValidatorClass.

I have explained all these properties in the next section.

Read More… 

ValidationSummary is derived directly from WebControl class and this control is used only for reporting all the validation error messages to the end user.

Read More… 

Validation Controls Common Properties and Methods 

The below given properties are common for the Validation Controls that are derived from BaseValidator Class. 

Apart from standard Font and other Formatting properties, the controls derived from BaseValidator class have the following properties in common. 

ControlToValidate – ID of the control which we are going to validate. The control must be developed using ValidatioPropertyAttribute. So if you develop any user control that may require validation then add this attribute to your control class. Read More on ValidatioPropertyAttribute from MSDN.    

Display – Display behavior of the error message in validation control, possible values are “None”, “Static”, ”Dynamic”. This property is explained in coming section

None - The validation message is never displayed. 

Static - The control displays an error message if validation fails. Space for the validation message is allocated in the layout of the page even if the input passes validation.  

Dynamic - The control displays an error message if validation fails. Space for the validation message is dynamically added to the page if validation fails. (If client-side validation is not active Static and Dynamic behave the same way). 

EnableClientScript – Use this property to enable or disable client-side validation. 
 
Enabled – Use this property to enable or disable the validation control. If this property is set to false then it will prevent validation being performed. 
 
ErrorMessage – Error message displayed in a ValidationSummary control when validation fails. 

Text – Error Message displayed in the validation control when validation fails. I have given another section on Difference between Text and ErrorMessage property

SetFocusOnError – Boolean value used to set focus to the control mentioned in the ControlToValidate when validation fails. 

ValidationGroup – The name of the validation group to which this validation control belongs, Detailed explanation is given in another section

IsValid – Boolean value that indicates the validation status.  

Read More…  

The BaseCompareValidator offers two main property in common in addition to those offered by the BaseValidator class.  

CultureInvariantValues - Boolean value indicating whether values are converted to a culture-neutral format before being compared.  
 
Type - Validation fails if the value cannot be converted to the specified data type, Possible values for Type are String, Integer, Double, Date, Currency.    

Note: Consider the culture of the web application while doing any comparison, especially when doing Date, Currency comparison.

Read More...  

The main method that’s common for all controls derived from BaseValidator class is Validate().  

Validate - Performs validation on the associated input control and updates the IsValid property, Detailed explanation is given in another section.

Read More… 

Client-Side and or Server-Side Validation

ASP.NET Validation Controls provides Client-side validation and Server-side validation. We can enable or disable the Client-side validation by setting a true/false value to the EnableClientScript property of the Validation Control. We don’t need to do anything special for Client-Side validation except setting the property EnableClientScript=true. By enabling Client-side validation we can reduce the round trips. 

If Client-side validation is enabled, the page includes references to script libraries that are used to perform the client-side validation. Every validation control makes sure that a standard block of client script is emitted into the page. This is actually just a small amount of script that includes a reference to code in a script library called WebUIValidation.js. Client-side validation uses the same error display mechanism as server-side validation. The Validation Controls automatically detects the client’s browser is enabled for client-side script validation. If it’s disabled then, client side validations are bypassed and validations are performed only on the web server. 

If you want to forcefully disable client-side validation and perform only server-side validation for the page then set the page attribute ClientTarget to DownLevel 

<%@ Page ClientTarget="DownLevel" %> 
Whereas setting the page attribute ClientTarget to UpLevel will force the controls to do both validations.  

<%@ Page ClientTarget="UpLevel" %>  

It’s better to leave this to Validation Controls instead of setting this attribute for forcefully enabling or disabling the validations on the page.    

Read More...      

Server Controls Property Relates to Validation Controls 

CausesValidation and ValidationGroup are the validation control related properties associated with some of the web server controls. I have explained the usage in an another section.

CausesValidation - Boolean value indicating whether the control causes validation to be performed on any controls that require validation when it receives focus. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done. By default CausesValidation is set to true. 

This property is available to the Button, ImageButton, and LinkButton Web server controls, the HtmlInputButton, HtmlInputImage, and HtmlButton HTML server controls, and controls that can automatically post back to the server such as the TextBox, CheckBox, ListControl, and BulletedList controls. 

ValidationGroup - The group of controls for which the server control causes validation when it posts back to the server  

Page Property or Method Relates to Server-Side Validation Controls

There are two properties and one method associated with page class related to validation controls, they are listed below. I have given an example for this in another section 

IsValid - Gets a value indicating whether page validation succeeded.  

Validators - This property will return a collection of validation controls in the page 

Read More…  
Validate method is the main method that will be used for validating the validation controls from server side. 

Validate - Validating the All Validation Controls with in the page   

Validate(String) - Validating Validation Controls for a specified validation group  

Read More… 

Client Side Property or Method Relates to Validation Controls  

ASP.NET validation controls provide functionality to perform validation using client script. When client-side validation is being performed, the user cannot post the page to the server if there are errors on the page thus reducing round-trips. The following properties are available in client-side.  

Page_IsValid - It's client side value used to identify the page is error free from the client side itself.   

Page_Validators - This property will return the collection of validation controls in the page. 

Page_ValidationActive - Indicates whether validation should take place. Set this variable to False to turn off validation programmatically.  

Isvalid -  Boolean value returns the associated validation control's validation failed or succeed. 

The following functions can be called from client-side for validation purpose. 

ValidatorValidate(val) - Takes a client-validator as input. Makes the validator check its input and update its display.  

ValidatorEnable(val, enable) - Enables or disables a client validator. Here "val" is the validation control and "enable" is the Boolean value. An example given in the section Conditional Validation  

ValidatorHookupControl(control, val) - Takes an input HTML element and a client-validator. Modifies or creates the element's change event so that it updates the validator when changed. This can be useful for custom validators that depend on multiple input values. 

Page_ClientValidate - Client-side function to validate all the Validation Controls with in the page  

Page_ClientValidate(ValGroup) -  Client-side function to validate all the Validation Controls with in the page  with the specified ValidationGroup. 

Read More...  

Validation Controls in depth    

Here I will give a detailed description of all validation controls with examples. All working codes are attached with this article, you may download the relevant files for your reference. 

The RequiredFieldValidator Control 

This is the simplest and most used control from validation control series. This control makes sure that the required field is entered by the user. For making a control mandatory we just need to tie a RequiredFieldValidator to that control. Leading and trailing spaces of the input value are removed before validation.

The only one property unique to this validation control is InitialValue.

InitialValue - This property can be used to mention the controls default value that needs to be changed with another value. RequiredFieldValidator ensures that the controls value is filled and not the initial value. 

Note: The InitialValue property does not set the default value for the input control. It indicates the value that you do not want the user to enter in the input control.

Read More... 

I will try to explain this control with the help of a sample. 

HTML

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" 
                ControlToValidate="txtEmail" ForeColor="Red" 
                ToolTip="Please enter your email" Display="Dynamic">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Phone
        </td>
        <td>
            <asp:TextBox ID="txtPhone" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:RequiredFieldValidator ID="rfvPjone" runat="server" 
                ControlToValidate="txtPhone" ForeColor="Red" 
                Text="Please enter your phone no" Display="Dynamic"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Profession
        </td>
        <td>
            <asp:DropDownList ID="drpProfession" runat="server" Width="140px">
                <asp:ListItem Selected="True">-Select-</asp:ListItem>
                <asp:ListItem>Writer</asp:ListItem>
                <asp:ListItem>Editor</asp:ListItem>
                <asp:ListItem>Engineer</asp:ListItem>
                <asp:ListItem>Cashier</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:RequiredFieldValidator ID="rfvProfession" runat="server" 
                ErrorMessage="Please select your profession"
                ForeColor="Red" ControlToValidate="drpProfession" 
                InitialValue="-Select-" Display="Dynamic"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Phone
        </td>
        <td>
            <asp:Label ID="lblPhone" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Profession
        </td>
        <td>
            <asp:Label ID="lblProfession" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

RequiredFieldValidator is used to make a field mandatory. Here I have three controls for capturing, Email, Phone, Profession. All fields are mandatory. to make the fields mandatory I have added RequiredFieldValidator for all the controls and mentioned the control name in the ControlToValidate property. 

To handle the default value in drop-down  I have specified the InitialValue of the Validation control to "-Select-". To succeed the validation we need to make sure that the control is having some other value than the value mentioned in InitialValue

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblPhone.Text = txtPhone.Text;
    lblProfession.Text = drpProfession.SelectedItem.Text;
}  

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side 

Output

Source Code  

Go to other downloads..    

The CompareValidator Control    

This control is used to compare the value entered in one control with another value (another control’s value, a database value, any specified Data Type value, any other value that you specify).

Note: If the input control value is empty then no validation will take place and will return IsValid true for this validator. If it's a mandatory field then add a RequiredFieldValidator also to that input control.  

The unique properties that offered by this control in addition to the properties of BaseValidator and BaseCompareValidator are Operator and ValueToCompare. 

ValueToCompare - The constant value to compare with the value entered by the user into the input control being validated. The default value is String.Empty.  

Note: Do not set both the ControlToCompare and ValueToCompare properties at the same time. You can either compare the value of an input control to another input control, or to a constant value. If both properties are set, the ControlToCompare property takes precedence.  

Operator - Use this property to specify the comparison operation to perform. The following are the comparison operations that are possible.  

Equal  - A comparison for equality between the values of the input control being validated and another control, or a constant value.

NotEqual - A comparison for inequality between the values of the input control being validated and another control, or a constant value.

GreaterThan - A comparison for greater than between the values of the input control being validated and another control, or a constant value.

GreaterThanEqual - A comparison for greater than or equal to between the values of the input control being validated and another control, or a constant value.

LessThan - A comparison for less than between the values of the input control being validated and another control, or a constant value. 

LessThanEqual - A comparison for less than or equal to between the values of the input control being validated and another control, or a constant value.

DataTypeCheck - A data type comparison of the value entered in the input control being validated and the data type specified by the BaseCompareValidator.Type property. Validation fails if the value cannot be converted to the specified data type.

Note: The ControlToCompare and ValueToCompare properties are ignored when 'DataTypeCheck' operator is used.  

Read More...  

Below is an example that will explain CompareValidator in detail.

HTML  

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" 
            ControlToValidate="txtEmail" ForeColor="Red" 
            ToolTip="Please enter your email" Display="Dynamic">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Confirm Email
        </td>
        <td>
            <asp:TextBox ID="txtConfirmEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvConfirmEmail" runat="server" ControlToValidate="txtConfirmEmail"
                ForeColor="Red" ToolTip="Please confirm your email">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvConfirmEmail" runat="server" ErrorMessage="Email do not match!"
                ControlToValidate="txtConfirmEmail" ControlToCompare="txtEmail" 
                Display="Dynamic" ForeColor="Red"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Age
        </td>
        <td>
            <asp:TextBox ID="txtAge" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvAge" runat="server" ControlToValidate="txtAge"
                ForeColor="Red" ToolTip="Please enter your age" Display="Dynamic">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvAge" runat="server" ErrorMessage="Please enter a number"
                ForeColor="Red" ControlToValidate="txtAge" Type="Integer" 
                Operator="DataTypeCheck" Display="Dynamic"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <br />
            <asp:CompareValidator ID="cvExperience" runat="server" 
                ErrorMessage="You must have 5 Year Exp or above to apply"
                Operator="GreaterThanEqual" ValueToCompare="5" ControlToValidate="txtExperience"
                Type="Integer" Display="Dynamic" ForeColor="Red"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Age
        </td>
        <td>
            <asp:Label ID="lblAge" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

CompareValidator is used to compare the control's value with any other value,that can be value of any other control , datatype, constant value. If you see here I have used multiple validation controls together, the reason is that the CompareValidator does not check for mandatory field thats why I have added a RequiredFieldValidator control. I have explained multiple validations in another section. 

Here I have written code for comparing two emails, age needs to be an integer value and experience needs to be greater than 5 Years. The corresponding validation controls Type, ValueToCompare, ControlToCompare, Operator etc properties are assigned accordingly.  

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblAge.Text = txtAge.Text;
    lblExperience.Text = txtExperience.Text + " Years";
}   

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side. 

Output

Source Code 

Go to other downloads..    

The RangeValidator Control

The RangeValidator server control is similar to the CompareValidator server control, This control is used to check that the user enters an input value that falls between two values. It is possible to check ranges within numbers, dates, and characters.

Note: If the input control value is empty then no validation will take place and will return IsValid true for this validator. If it's a required field then add a RequiredFieldValidator also.   

The unique properties that offered by this control in addition to the properties of BaseValidator and BaseCompareValidator are MinimumValue and MaximumValue

MaximumValue - Use this property to specify the maximum value of the validation range.

MinimumValue - Use this property to specify the minimum value of the validation range 

Read More...  
Sample:

HTML 

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvExperience" runat="server" ControlToValidate="txtExperience"
                ForeColor="Red" ToolTip="Please enter your experience" Display="Dynamic">*</asp:RequiredFieldValidator>
            <br />
            <asp:RangeValidator ID="rvExperience" runat="server" ControlToValidate="txtExperience"
                Type="Integer" ErrorMessage="You must have 5 to 15 Years of Exp to apply" MaximumValue="15"
                MinimumValue="5" Display="Dynamic" ForeColor="Red"></asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Grade
        </td>
        <td>
            <asp:DropDownList ID="drpGrade" runat="server" Width="140px">
                <asp:ListItem Selected="True">-Select-</asp:ListItem>
                <asp:ListItem>A</asp:ListItem>
                <asp:ListItem>B</asp:ListItem>
                <asp:ListItem>C</asp:ListItem>
                <asp:ListItem>D</asp:ListItem>
                <asp:ListItem>E</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:RangeValidator ID="rvGrade" runat="server" ControlToValidate="drpGrade" 
            ErrorMessage="Your accademic grade needs to be between A and C to apply"
                MaximumValue="C" MinimumValue="A" Display="Dynamic"  ForeColor="Red"></asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Grade
        </td>
        <td>
            <asp:Label ID="lblGrade" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

RangeValidator ensures that the control's value is in a given range. In this example the criteria is, Experience needs to be with 5 years to 15 years and grade needs to be between A & B. The validation controls values MinimumValue and MaximumValues are assigned accordingly. 

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblExperience.Text = txtExperience.Text + " Years";
    lblGrade.Text = drpGrade.Text;
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side.

Output

Source Code

Go to other downloads..   

The RegularExpressionValidator Control 

This control check the user's input based on a pattern defined by a regular expression. This validation control is very helpful when checking email address, phone number, zip code etc, Usually in the previous time we used to do considerably big functions for this kind of validations. 

Note: The validation will not fail if the input control is empty. Use the RequiredFieldValidator control to make the field as required.

A great place on the Internet to find free regular expressions is the RegEx Library

The only one unique property that offered by this control in addition to the properties of BaseValidator is ValidationExpression

ValidationExpression - A string that specifies the regular expression used to validate a field for format. 

Read More... 
The following example demonstrates the usage of RegularExpressionValidator. 

HTML

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:RegularExpressionValidator
                ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" Display="Dynamic" ErrorMessage="Please enter a valid email address"
                ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

Here The RegularExpressionValidator is used to validate an email Id and the validation pattern is given in the ValidationExpression property. 

Code-Behind

protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side 

Output

Source Code

Go to other downloads..    

The CustomValidator Control 

The CustomValidator server control enables you to develop your own custom server-side or client-side validations. At times, you may want to compare the user's input to a value in a database, or to determine whether his input conforms to some arithmetic validation that you are looking for. You can do all this and more by using this type of validation control.

Two unique properties and one unique event handler are associated with CustomValidator. They are,

ClientValidationFunction - Name of the custom client-side script function used for validation.  

Note: The script must be in a language that the browser supports, such as VBScript or JScript.    

ValidateEmptyText - Boolean value indicating whether empty text should be validated. setting this property to false will cause the validation control to bypass the validation in-case of empty string .  

OnServerValidate - Specifies the name of the server-side validation script function to be executed.  

Read More... 
We can understand these properties with the help of a sample.

JavaScript

function clientValidateUserName(sender, args) {
    args.IsValid = false;
    var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
    if (!reg.test(args.Value)) {
        args.IsValid = true;
    } 
} 

The above JavaScript will be called in client-side by the CustomValidator. This function checks the entered value.If it's an integer value then it will set the IsValid property to false and thus custom validator's validation will get failed in client side. If it's succeeded then it will send to the server-side validation method "serverValidateUserName".  

HTML 

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            User
        </td>
        <td>
            <asp:TextBox ID="txtUserName" runat="server" Width="140px"></asp:TextBox>
            <br />
            <asp:CustomValidator ID="customVUserName" runat="server" ControlToValidate="txtUserName"
                Display="Dynamic" ErrorMessage="*" ClientValidationFunction="clientValidateUserName"
                OnServerValidate="serverValidateUserName" 
                Text="The User Name you entered is incorrect or not an admin."
                ValidateEmptyText="true" ForeColor="Red" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
                User
        </td>
        <td>
            <asp:Label ID="lblUserName" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

Here the JavaScript function that we defined mentioned before is assigned in ClientValidationFunction property and the server-side handler (method) is assigned in  OnServerValidate property. 

Code-Behind 

protected void btnLogin_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblUserName.Text = txtUserName.Text + " is a valid admin user";
    }
    else
    {
        lblUserName.Text = txtUserName.Text + " is not a valid admin user";
    }
}
protected void serverValidateUserName(object sender, ServerValidateEventArgs args)
{
    args.IsValid = false;
    if (!string.IsNullOrEmpty(args.Value))
    {
        args.IsValid = AvailableAdmins.Contains(args.Value);
    }
}
public string[] AvailableAdmins { get { return new string[] { "Shemeer", "Aydin", "Dave" }; } } 

In "serverValidateUserName" method it's checking the entered user name is available in the predefined list, If not it the validation will fail otherwise validation will get succeeded.  

Output

Source Code 

Go to other downloads..   

The ValidationSummary Control    

The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property.

The error message displayed in this control is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed for that validation control.

The unique properties that offered by ValidationSummary control are follows,

DisplayMode - Use this property to specify the display format of a ValidationSummary control. The summary can be displayed as a list, as a bulleted list, or as a single paragraph.The default is BulletList.  

List - Validation summary displayed in a list.

BulletList - Validation summary displayed in a bulleted list.

SingleParagraph - Validation summary displayed in a single paragraph. 

HeaderText - The header text displayed at the top of the summary.

ShowMessageBox - A Boolean value that specifies whether the summary should be displayed in a message box or not. 

ShowSummary - A Boolean value that specifies whether the ValidationSummary control should be displayed or hidden. 

Read More... 
Below given example demonstrates how to use a ValidationSummary control to summarize the error messages from all validation controls on a Web page and display them in a bulleted list with a HeaderText.

HTML 

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic" 
                ErrorMessage="Please enter your email">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Age
        </td>
        <td>
            <asp:TextBox ID="txtAge" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvAge" runat="server" ControlToValidate="txtAge"
                ForeColor="Red" ToolTip="Please enter your age" Display="Dynamic" 
                ErrorMessage="Please enter your age">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvAge" runat="server" ErrorMessage="Please enter a number"
                ForeColor="Red" ControlToValidate="txtAge" Type="Integer" Operator="DataTypeCheck"
                Display="Dynamic"></asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:TextBox ID="txtExperience" runat="server" Width="40px" MaxLength="2"></asp:TextBox>
            <br />
            <asp:CompareValidator ID="cvExperience" runat="server" 
            ErrorMessage="You must have 5 Year Exp or above to apply"
                Operator="GreaterThanEqual" ValueToCompare="5" 
                ControlToValidate="txtExperience"
                Type="Integer" Display="Dynamic" ForeColor="Red" 
                ToolTip="You must have 5 Year Exp or above to apply">*</asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:ValidationSummary ID="vsSample" runat="server" 
            DisplayMode="BulletList" ShowMessageBox="true"
                ShowSummary="true" ForeColor="Red" 
                HeaderText="Correct the following errors." />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" 
            OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Age
        </td>
        <td>
            <asp:Label ID="lblAge" runat="server"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            Experience
        </td>
        <td>
            <asp:Label ID="lblExperience" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

Here by using ValidationSummary Control we are showing all the validation error messages in the browser and in alert message.

We have used the properties DisplayMode="BulletList", ShowMessageBox="true", ShowSummary="true", ForeColor="Red" and HeaderText="Correct the following errors." You can see the expected output in the output section. 

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
    lblAge.Text = txtAge.Text;
    lblExperience.Text = txtExperience.Text + " Years";
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side  

Output 

Source Code 

Go to other downloads..   

Understanding Display, Enabled, Visible Property 

I have already given a short description about these properties in the over-view section. Here I will compare the different options available with Display property and rendering differences when we use these properties.

The three options available for Display property are None, Static, Dynamic.

When we use None, the validator does not display anything directly but error message will be displayed if a ValidationSummary control used in that page. Usually Display property set to None, when we don’t want to show the message near to the control and instead we like to show in a specific area in the page.

In-case of Static the control will display an error message if validation fails. Space for the validation is allocated in the page layout  all the time. The Static property will emit a single nonbreaking space ("&nbsp") next to the control associated with the ValidationControl., so that table cells containing only validators do not collapse to nothing when valid.

If the value is set to Dynamic then nothing at all displays when the input is valid. Space for the validation message is dynamically added to the page if validation fails. If client-side validation is not active Static and Dynamic behave the same way. 

Visible and Enabled property are very much similar. If we set either one to false for a validator means that not only does not it not display anything, it is does not function either. It is not evaluated, does not affect page validity, and does not put errors in the summary. The slight difference for the Enabled property is in client-side validation, a disabled validator is still sent to the browser, but in a disabled state. You can activate it with the ValidatorEnable function in client script.

Read More...  

Difference between Text and ErrorMessage property

The Text Property is used to specify the text to display in a validation control when validation fail whereas the ErrorMessage property are used specify the text to display in the ValidationSummary control when validation fails for the current validation control.

The text property can be constructed in two ways,

<asp:RequiredFieldValidator id="RequiredFieldValidator1" 
runat="server" Text="Required!" 
ControlToValidate="TextBox1">
</asp:RequiredFieldValidator>  

Or  

<asp:RequiredFieldValidator id="RequiredFieldValidator1" 
runat="server" ControlToValidate="TextBox1">
Required!
</asp:RequiredFieldValidator>  

The below code shows an example of ErrorMessage property.

<asp:RequiredFieldValidator id="RequiredFieldValidator1" 
runat="server" ControlToValidate="TextBox1" ErrorMessage="Please enter the Textbox1 value">
Required!
</asp:RequiredFieldValidator>  

If you want to show the same text in validation control and validation summary in-case of validation failure, then use ErrorMessage. If you want to show different text in validation control and validation summary if the validation fails, then use Text property and ErrorMessage Property.

One ideal way of presenting this validation-error information is to have an asterisk (*) appear next to the HTML form fields in question, while the error messages stating what is wrong with the input appear in the list of errors shown within the ValidationSummary control. 

When using a ValidationSummary control, use the ErrorMessage property to specify the text to display in the ValidationSummary control when validation fails for the current validation control. To specify the text to display in the validation control itself, use the Text property.

If you set the ErrorMessage property without setting the Text property, the value of the ErrorMessage property is also displayed in the validation control. If ErrorMessage is not set for the validation control then ValidationSummary won’t show any messages related to that validation control.

Importance of CausesValidation and ValidationGroup property 

Here I'm explaining the importance of CausesValidation and ValidationGroup with the help of a small example.  

The Problem

 

The problem in the above User Login Page is that it's validating all the controls all the time. whereas the expected functionality is to validate the Sign-In section only when clicking on "Sign In" button, clear the Sign-In control when clicking on "Reset" button and validate the Sign-Up section only when clicking "Sign Up" button.  

HTML 

<table class="vcTableBig">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtSignInEmail" runat="server" Width="140px" 
                ValidationGroup="SignIn"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvSignInEmaill" runat="server" 
                ControlToValidate="txtSignInEmail"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic" 
                ValidationGroup="SignIn">*</asp:RequiredFieldValidator>
        </td>
        <td style="background-color: Silver">
        </td>
        <td style="font-weight: bold">
            Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" Width="140px" ValidationGroup="SignUp"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic" 
                ValidationGroup="SignUp">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Password
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" Width="140px" TextMode="Password" 
                ValidationGroup="SignIn"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvPjone" runat="server" 
                ControlToValidate="txtPassword"
                ForeColor="Red" Text="*" Display="Dynamic" 
                ValidationGroup="SignIn"></asp:RequiredFieldValidator>
        </td>
        <td style="background-color: Silver">
        </td>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtSignUpEmail" runat="server" Width="140px" 
                ValidationGroup="SignUp"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvSignUpEmail" runat="server" 
                ControlToValidate="txtSignUpEmail"
                ForeColor="Red" Text="*" Display="Dynamic" 
                ValidationGroup="SignUp"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td align="center" colspan="2">
            <asp:Button ID="btnSignIn" runat="server" Text="Sign In" 
                OnClick="btnSignIn_Click" ValidationGroup="SignIn">
            </asp:Button>
            <asp:Button ID="btnSignInReset" runat="server" Text="Reset" 
                OnClick="btnSignInReset_Click"
                CausesValidation="false"></asp:Button>
        </td>
        <td style="background-color: Silver">
        </td>
        <td colspan="2" align="center">
            <asp:Button ID="btnSignUp" runat="server" Text="Sign Up" 
                OnClick="btnSignUp_Click" ValidationGroup="SignUp">
            </asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            Logged in as:
        </td>
        <td style="background-color: Silver">
        </td>
        <td colspan="2" align="center">
            Sign up request sent to:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td class="style1">
            <asp:Label ID="lblSignInEmail" runat="server"></asp:Label>
        </td>
        <td style="background-color: Silver">
        </td>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblSignUpEmail" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

To over come the above problem, I have added Validation Group property to the controls in particluar sections and CausesValidation property set to false for the "Reset" button to bypass the validation. 

Code-Behind  

protected void btnSignIn_Click(object sender, EventArgs e)
{
    lblSignInEmail.Text = txtSignInEmail.Text;
}
protected void btnSignInReset_Click(object sender, EventArgs e)
{
    txtSignInEmail.Text = string.Empty;
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    lblSignUpEmail.Text = txtSignUpEmail.Text;
    txtSignUpEmail.Text = string.Empty;
    txtName.Text = string.Empty;
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side. 

Output

 

Source Code

Go to other downloads..    

Showing validation message as an Image/Icon

In some cases we might want to show image/icon instead of usual text error messages. We can simply acheive this as the Text and Error Message property accepts HTML tags. we just need to set the corresponding html tag in the text property. 

HTML

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvName" runat="server" 
                ControlToValidate="txtName"
                ToolTip="Please enter your Name" Display="Dynamic" 
                EnableClientScript="false"><img src="error.ico"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Name
        </td>
        <td>
            <asp:Label ID="lblName" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

In this sample, Name is a mandatory field and we need to show error icon incase of validation error. As you can see in the HTML the <img> src attribute is set to the icon file. So in-case of error the icon will be shown in the UI. This works if the EnableClientScript=true/false conditions 

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblName.Text = txtName.Text;
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side  

Output

  

Source Code 

Go to other downloads..   

Adding Sound to validation control 

If you want to add validation error sound for a validation control then you need to add the corresponding html tag and refer the audio file.You can also add any other HTML to the Text and ErrorMessage property. 

HTML

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
                ToolTip="Please enter your Name" Display="Dynamic" 
                EnableClientScript="false" Text='<bgsound src="error.mp3">'></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Name
        </td>
        <td>
            <asp:Label ID="lblName" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

Here we marked Name as mandatory field by adding RequiredFieldValidator to enable the sound we have to add the <bgsound> tag or any other similiar tag. This works only if the EnableClientScript=false;

Note:The HTML Background Sound Element (<bgsound>) is an Internet Explorer element associating a background sound with a page. So the above code will work only with IE, you may need to change the HTML tag corresponding to other browsers.  

Note: HTML 5 - The <bgsound> tag should be avoided because it has been deprecated. The <audio> tag should be used instead. 

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblName.Text = txtName.Text;
}  

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side.

Output  

Beeeep....

Try yourself Smile | <img src= 

Source Code 

Go to other downloads..  

Conditional Validation 

If you ever implimented validation control in your web application then you might have faced this requirement at-least once. 

I will take an example to explain the conditional validation, In this Example, I need to capture the phone number of a user from some defined options, Two options are available, they are mobile number and landline number. The user can select one from the option and need to enter the corresponding number in the provided control. We need to make sure that the specified number is entered by the user while submitting the form.

In this case, we just need to enable the validation control which needs to get evaluated and disable the other one. 

You can acheive this by using client-side function ValidatorEnable() or from server-side by changing the Validator Control's Enabled=true/false

JavaScript 

function changeValidationSettings() {
    var rfvM = document.getElementById("<%=rfvMobile.ClientID %>");
    var rfvL = document.getElementById("<%=rfvLandline.ClientID %>");
    var rdoMobile = document.getElementById("<%=rdoMobile.ClientID %>");
        ValidatorEnable(rfvM, rdoMobile.checked);
        ValidatorEnable(rfvL, !rdoMobile.checked);          
} 

This JavaScript method is used to enable or disable the validation control associated with the input control.

This function will be called when the option button onclick client-side event is fired, according to the option selected this method will enable/disable the corresponding validation controls . To enable/disable the control we have used the ValidatorEnable() method in client-side.  

HTML 

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Phone Number
        </td>
        <td>
            <asp:RadioButton ID="rdoMobile" runat="server" Text="Mobile" Checked="True" 
                onclick="changeValidationSettings();" GroupName="Phone" />
            <asp:RadioButton ID="rdoLandline" runat="server" Text="Landline" 
                onclick="changeValidationSettings();" GroupName="Phone" />
        </td>
    </tr>
    <tr>
        <td>
            Mobile
        </td>
        <td>
            <asp:TextBox ID="txtMobile" runat="server" Width="140px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvMobile" runat="server" ControlToValidate="txtMobile"
                ForeColor="Red" ToolTip="Please enter your Mobile" Display="Dynamic" 
                ErrorMessLandline="Please enter your Mobile">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            Landline
        </td>
        <td>
            <asp:TextBox ID="txtLandline" runat="server" Width="140px" MaxLength="10"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvLandline" runat="server" ControlToValidate="txtLandline"
                ForeColor="Red" ToolTip="Please enter your Landline" Display="Dynamic" 
                ErrorMessLandline="Please enter your Landline">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Phone Number
        </td>
        <td>
            <asp:Label ID="lblPhone" runat="server"></asp:Label>
        </td>
    </tr>
</table>  

The option buttons client-side onclick event is tied to the javascript method "changeValidationSettings" and this method will take care of the conditional validation from client-side.  

Code-Behind

protected void Page_Load(object sender, EventArgs e)
{
    rfvMobile.Enabled = rdoMobile.Checked;
    rfvLandline.Enabled = !rdoMobile.Checked;
}
protected void btnSave_Click(object sender, EventArgs e)
{
    lblPhone.Text = rdoMobile.Checked ? txtMobile.Text : txtLandline.Text;
}  

In "btnSave_Click" I'm just showing the captured value in corresponding to the number entered and in Page_Load I have enabled the default/selected option's validation control and disabled the other. This  "btnSave_Click" event will not fire if the validation fails in client-side.    

Output 

 

Source Code 

Go to other downloads..    

Multiple Validations  

There are situations where we want to have multiple validations performed on a single control. Here I will expalin Multiple Validation with a very simple example   

HTML 

<table class="vcTable">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtEmail" runat="server" Width="150px"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" ToolTip="Please enter your Email" Display="Dynamic">*</asp:RequiredFieldValidator>
            <br />
            <asp:CompareValidator ID="cvEmail" runat="server" ErrorMessage="Email can not be noname@nodomain.com"
                Operator="NotEqual" ValueToCompare="noname@nodomain.com" ControlToValidate="txtEmail"
                Type="String" Display="Dynamic" ForeColor="Red"></asp:CompareValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail"
                ForeColor="Red" Display="Dynamic" ErrorMessage="Please enter a valid email address"
                ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"></asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            You have entered:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblEmail" runat="server"></asp:Label>
        </td>
    </tr>
</table> 

Here email is a mandatory field, it should be a valida email and the email cann't be "noname@nodomain.com". To validate this three conditions I have added RequiredFieldValidator,CompareValidator and a RegularExpressionValidator

If we want we can use InitialValue of RequiredFieldValidator to set the "noname@nodomain.com". but I have used CompareValidator to have a different ErrorMessage

Code-Behind 

protected void btnSave_Click(object sender, EventArgs e)
{
    lblEmail.Text = txtEmail.Text;
} 

In code behind I'm just showing the captured value in corresponding labels. This code block will not fire if the validation fails in client-side   

Output

 

Source Code

Go to other downloads..   

Page.Validate() and IsValid  

We can validate the controls from server-side by using Page.Validate() method.The Validate method is fired automatically by controls that have the CausesValidation property set to true. As I mentioned earlier CausesValidation is default by true.

If the sender control which have the CausesValidation set to true have some ValidationGroup specified then the page automatically calls the overloaded Page.Validate(ValidationGroup) method.

In-case if the sender control's CausesValidation set to false then validation will bypass from the client-side. If you want to validate the controls in server in-case of CausesValidation=false then you must call the Validate() method specifically. The Page.IsValid property will tell you the validation is success or failure. 

HTML 

<table class="vcTableBig">
    <tr>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtSignInEmail" runat="server" Width="140px" 
                ValidationGroup="SignIn"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvSignInEmaill" runat="server" 
                ControlToValidate="txtSignInEmail"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic" 
                ValidationGroup="SignIn">*</asp:RequiredFieldValidator>
        </td>
        <td style="background-color: Silver">
        </td>
        <td style="font-weight: bold">
            Name
        </td>
        <td>
            <asp:TextBox ID="txtName" runat="server" Width="140px" ValidationGroup="SignUp"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
                ForeColor="Red" ToolTip="Please enter your email" Display="Dynamic" 
                ValidationGroup="SignUp">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td style="font-weight: bold">
            Password
        </td>
        <td>
            <asp:TextBox ID="txtPassword" runat="server" Width="140px" TextMode="Password" 
                ValidationGroup="SignIn"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvPjone" runat="server" 
                ControlToValidate="txtPassword"
                ForeColor="Red" Text="*" Display="Dynamic" 
                ValidationGroup="SignIn"></asp:RequiredFieldValidator>
        </td>
        <td style="background-color: Silver">
        </td>
        <td style="font-weight: bold">
            Email
        </td>
        <td>
            <asp:TextBox ID="txtSignUpEmail" runat="server" Width="140px" 
                ValidationGroup="SignUp"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvSignUpEmail" runat="server" 
                ControlToValidate="txtSignUpEmail"
                ForeColor="Red" Text="*" Display="Dynamic" 
                ValidationGroup="SignUp"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td align="center" colspan="2">
            <asp:Button ID="btnSignIn" runat="server" Text="Sign In" 
                OnClick="btnSignIn_Click" ValidationGroup="SignIn">
            </asp:Button>
            <asp:Button ID="btnSignInReset" runat="server" Text="Reset" 
                OnClick="btnSignInReset_Click"
                CausesValidation="false"></asp:Button>
        </td>
        <td style="background-color: Silver">
        </td>
        <td colspan="2" align="center">
            <asp:Button ID="btnSignUp" runat="server" Text="Sign Up" CausesValidation="false" 
                OnClick="btnSignUp_Click" ValidationGroup="SignUp">
            </asp:Button>
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            Logged in as:
        </td>
        <td style="background-color: Silver">
        </td>
        <td colspan="2" align="center">
            Sign up request sent to:
        </td>
    </tr>
    <tr>
        <td>
            Email
        </td>
        <td class="style1">
            <asp:Label ID="lblSignInEmail" runat="server"></asp:Label>
        </td>
        <td style="background-color: Silver">
        </td>
        <td>
            Email
        </td>
        <td>
            <asp:Label ID="lblSignUpEmail" runat="server"></asp:Label>
        </td>
    </tr>
</table>     

Here I have created separate ValidationGroups for SignUp and SignIn section. The SignUp and Reset button's CausesValidation property are set to false.  

Code-Behind

protected void btnSignIn_Click(object sender, EventArgs e)
{
    //Page.Validate("SignIn"); 
    //is not required as CausesValidation property 
    //of the Button control is true.
    //Proceed only if the vaidation is successfull
    if (Page.IsValid)
    {
        lblSignInEmail.Text = txtSignInEmail.Text;
    }           
}
protected void btnSignInReset_Click(object sender, EventArgs e)
{
    txtSignInEmail.Text = string.Empty;
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    Validate("SignUp");
    if (IsValid)
    {
        lblSignUpEmail.Text = txtSignUpEmail.Text;
        txtSignUpEmail.Text = string.Empty;
        txtName.Text = string.Empty;
    }
} 

In server-side SignIn button click will automatically call the Page.Validate("SignIn") method as CausesValidation property is set to true, and we are checking the Page.IsValid property to know the validation was successful or not. 

Reset button will not call any validate method as CausesValidation is set to false

In SignUp button' click we are specifically calling the Validate("SignUp") method to validate the ValidationControls in that group and to set the Page.IsValid property. Once the method is called then we are checking the Page.IsValid property to identify the validation was success or failure.  

Output 

 

Source Code 

Go to other downloads..    

Download Sample Code(s) 

Al source codes are given in VS 2005, VS 2008 and VS 2010 solutions, you may download the relevant files for you.  

References

I have added references in-line to all sections.  

History  

  • 25th July 2012 Initial draft.   
  • 11th Aug 2012 Initial release.   

Summary  

I have tried to explore the ASP.NET Validation controls in detail with the help of samples. I hope you have enjoyed this article and got some value addition to your knowledge.

I have put my time and efforts on all of my articles, please don't forget to mark your votessuggestions and feedback to improve the quality of this and upcoming articles.

Thanks for reading. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shemeer NS
Software Developer (Senior)
India India
Technology Specialist | CodeProject MVP | Visual Studio Gallery Contributor | Author | Geek | Netizen | Husband | ChessPlayer
 
Most of my articles are listed on top 5 of the respective 'Best articles of the month' and some of my articles are published on ASP.NET WebSite's Article of the Day section.
 
Check my contributions in Visual Studio Gallery and Code Project
 
Technical Blog: http://www.shemeerns.com
Facebook: http://facebook.com/shemeernsblog
Twitter : http://twitter.com/shemeerns
Google+ : http://google.com/+Shemeernsblog
Follow on   Twitter   Google+

Comments and Discussions

 
Generalthank Pinmemberpethaperumal12331-Mar-14 0:05 
SuggestionExcellent PinmemberMember 1057247826-Feb-14 23:18 
QuestionAsp.net validation ctrl PinmemberMember 1060981219-Feb-14 7:29 
QuestionMy Vote of 5 Pinmembervipz00715-Oct-13 19:40 
Questionmultiple validation groups and buttons Pinmembertechie201311-Jul-13 0:36 
AnswerRe: multiple validation groups and buttons Pinmembertechie201311-Jul-13 1:42 
QuestionValidationGroup Pinmembertechie20135-Jul-13 2:57 
AnswerRe: ValidationGroup PinmvpShemeer NS5-Jul-13 20:11 
GeneralMy vote of 5 Pinmembertechie20135-Jul-13 2:51 
GeneralMy vote of 5 Pinmemberwsc09183-Jul-13 16:39 
GeneralMy vote of 5 PinmemberAbhishek Ranjan Srivastava1-Apr-13 20:42 
GeneralMy Vote of 5 Pinmemberpatel_pratik11-Feb-13 18:51 
GeneralMy vote of 5 PinmemberMember 408914214-Jan-13 21:59 
GeneralRe: My vote of 5 PinmvpShemeer NS19-Jan-13 19:36 
GeneralGood article Pinmemberlavy_oly_200513-Sep-12 2:08 
GeneralRe: Good article PinmemberShemeer NS27-Sep-12 10:14 
Thank you...
QuestionExcellent PinmemberSunasara Imdadhusen12-Sep-12 21:55 
AnswerRe: Excellent PinmemberShemeer NS16-Sep-12 20:37 
GeneralMy vote of 5 Pinmembergaille28-Aug-12 6:25 
GeneralMy vote of 5 PinmemberVince P.14-Aug-12 9:42 
GeneralMy vote of 5 PinmemberMember 178709914-Aug-12 4:52 
GeneralMy vote of 5 PinmemberPritesh Aryan13-Aug-12 5:14 
GeneralMy vote of 5 PinmemberMember 88469613-Aug-12 1:50 
Questiongood Pinmembersherafu13-Aug-12 1:36 
AnswerRe: good PinmemberShemeer NS16-Sep-12 20:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 11 Aug 2012
Article Copyright 2012 by Shemeer NS
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid