Validation Controls In ASP.NET

Why we use validation controls?

Validation is important part of any web application. User's input must always be validated before sending across different layers of the application.
Validation controls are used to,
  • Implement presentation logic.
  • To validate user input data.
  • Data format, data type and data range is used for validation.
Validation is of two types
  1. Client Side
  2. Serve Side
Client side validation is good but we have to be dependent on browser and scripting language support.
Client side validation is considered convenient for users as they get instant feedback. The main advantage is that it prevents a page from being postback to the server until the client validation is executed successfully.
For developer point of view serve side is preferable because it will not fail, it is not dependent on browser and scripting language.
You can use ASP.NET validation, which will ensure client, and server validation. It work on both end; first it will work on client validation and than on server validation. At any cost server validation will work always whether client validation is executed or not. So you have a safety of validation check.
For client script .NET used JavaScript. WebUIValidation.js file is used for client validation by .NET

Validation Controls in ASP.NET

An important aspect of creating ASP.NET Web pages for user input is to be able to check that the information users enter is valid. ASP.NET provides a set of validation controls that provide an easy-to-use but powerful way to check for errors and, if necessary, display messages to the user.
There are six types of validation controls in ASP.NET
  1. RequiredFieldValidation Control
  2. CompareValidator Control
  3. RangeValidator Control
  4. RegularExpressionValidator Control
  5. CustomValidator Control
  6. ValidationSummary
The below table describes the controls and their work,
Validation Control Description
RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the value of another input control or to a fixed value
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified pattern
CustomValidator Allows you to write a method to handle the validation of the value entered
ValidationSummary Displays a report of all validation errors occurred in a Web page

All validation controls are rendered in form as <span> (label are referred as <span> on client by server)
Important points for validation controls
  • ControlToValidate property is mandatory to all validate controls.
  • One validation control will validate only one input control but multiple validate control can be assigned to a input control.
Validation Properties
Usually, Validation is invoked in response to user actions like clicking submit button or entering data. Suppose, you wish to perform validation on page when user clicks submit button.
Server validation will only performed when CauseValidation is set to true.
When the value of the CausesValidation property is set to true, you can also use the ValidationGroup property to specify the name of the validation group for which the Button control causes validation.
Page has a Validate() method. If it is true this methods is executed. Validate() executes each validation control.
To make this happen, simply set the CauseValidation property to true for submit button as shown below:
<asp:Button ID="Button2" runat="server" Text="Submit" CausesValidation=true />
Lets understand validation controls one by one with practical demonstration:

RequiredFieldValidation Control

The RequiredFieldValidator control is simple validation control, which checks to see if the data is entered for the input control. You can have a RequiredFieldValidator control for each form element on which you wish to enforce Mandatory Field rule.
  1. <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
  2. Style="top: 98px; left: 367px; position: absolute; height: 26px; width: 162px" 
  3. ErrorMessage="password required" ControlToValidate="TextBox2">
  4. </asp:RequiredFieldValidator>  

CompareValidator Control

The CompareValidator control allows you to make comparison to compare data entered in an input control with a constant value or a value in a different control.
It can most commonly be used when you need to confirm password entered by the user at the registration time. The data is always case sensitive.
  1. <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;  
  2.         left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
  3.         ControlToValidate="TextBox3"></asp:RequiredFieldValidator>  

RangeValidator Control

The RangeValidator Server Control is another validator control, which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.
  1. <asp:RangeValidator ID="RangeValidator1" runat="server" 
  2. Style="top: 194px; left: 365px; position: absolute; height: 22px; width: 105px" 
  3. ErrorMessage="RangeValidator" ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>  

RegularExpressionValidator Control

A regular expression is a powerful pattern matching language that can be used to identify simple and complex characters sequence that would otherwise require writing code to perform.
Using RegularExpressionValidator server control, you can check a user's input based on a pattern that you define using a regular expression.
It is used to validate complex expressions. These expressions can be phone number, email address, zip code and many more. Using Regular Expression Validator is very simple. Simply set the ValidationExpression property to any type of expression you want and it will validate it.
If you don't find your desired regular expression, you can create your custom one.
In the example I have checked the email id format:
  1. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234px;  
  2.         left: 366px; position: absolute; height: 22px; width: 177px"   
  3.         ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"   
  4.         ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
The complete code for the above 4 controls is as,
Default.aspx Design
Default.aspx Source code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">  
  3. <html xmlns="">  
  4. <head runat="server">  
  5.     <title>Untitled Page</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         <asp:Label ID="Label3" runat="server" Style="top: 241px; left: 70px; position: absolute;  
  11.             height: 22px; width: 128px; bottom: 282px;" Text="Enter your email id:"></asp:Label>  
  12.         <asp:Label ID="Label1" runat="server" Style="top: 54px; left: 74px; position: absolute;  
  13.             height: 22px; width: 128px" Text="Enter your name:"></asp:Label>  
  14.         <asp:TextBox ID="TextBox1" runat="server" Style="top: 54px; left: 221px; position: absolute;  
  15.             height: 22px; width: 128px; right: 396px;"></asp:TextBox>  
  16.         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Style="top: 56px;  
  17.             left: 378px; position: absolute; height: 22px; width: 128px" ErrorMessage="RequiredFieldValidator"  
  18.             ControlToValidate="TextBox1">name is   
  19.         mandatory </asp:RequiredFieldValidator>  
  20.     </div>  
  21.     <p>  
  22.         <asp:Button ID="Button1" runat="server" Style="top: 311px; left: 267px; position: absolute;  
  23.             height: 26px; width: 61px" Text="Submit" />  
  24.     </p>  
  25.     <asp:TextBox ID="TextBox3" runat="server" Style="top: 145px; left: 217px; position: absolute;  
  26.         height: 22px; width: 131px" TextMode="Password"></asp:TextBox>  
  27.     <p>  
  28.         <asp:TextBox ID="TextBox2" runat="server" Style="top: 101px; left: 218px; position: absolute;  
  29.             height: 22px; width: 131px" TextMode="Password"></asp:TextBox>  
  30.         <asp:Label ID="Label4" runat="server" Style="top: 105px; left: 74px; position: absolute;  
  31.             height: 22px; width: 128px" Text="Password"></asp:Label>  
  32.         <asp:TextBox ID="TextBox5" runat="server" Style="top: 239px; left: 210px; position: absolute;  
  33.             height: 22px; width: 134px"></asp:TextBox>  
  34.     </p>  
  35.     <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 98px;  
  36.         left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
  37.         ControlToValidate="TextBox2"></asp:RequiredFieldValidator>  
  38.     <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 145px;  
  39.         left: 367px; position: absolute; height: 26px; width: 162px" ErrorMessage="password required"  
  40.         ControlToValidate="TextBox3"></asp:RequiredFieldValidator>  
  41.     <asp:CompareValidator ID="CompareValidator1" runat="server" Style="top: 149px; left: 512px;  
  42.         position: absolute; height: 26px; width: 162px" ErrorMessage="CompareValidator"  
  43.         ControlToValidate="TextBox3" ValueToCompare="hello"></asp:CompareValidator>  
  44.     <p>  
  45.         <asp:Label ID="Label5" runat="server" Style="top: 148px; left: 71px; position: absolute;  
  46.             height: 22px; width: 128px; bottom: 375px;" Text="Confirm Password"></asp:Label>  
  47.         <asp:TextBox ID="TextBox4" runat="server" Style="top: 194px; left: 212px; position: absolute;  
  48.             height: 22px; width: 140px"></asp:TextBox>  
  49.         <asp:Label ID="Label6" runat="server" Style="top: 194px; left: 71px; position: absolute;  
  50.             height: 22px; width: 128px; bottom: 329px;" Text="Enter your age:"></asp:Label>  
  51.     </p>  
  52.     <asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 194px; left: 365px;  
  53.         position: absolute; height: 22px; width: 105px" ErrorMessage="RangeValidator"  
  54.         ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer"></asp:RangeValidator>  
  55.     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Style="top: 234px;  
  56.         left: 366px; position: absolute; height: 22px; width: 177px"   
  57.         ErrorMessage="RegularExpressionValidator" ControlToValidate="TextBox5"   
  58.         ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>  
  59.     </form>  
  60. </body>  
  61. </html>  
CustomValidator Control
You can solve your purpose with ASP.NET validation control. But if you still don't find solution you can create your own custom validator control.
The CustomValidator Control can be used on client side and server side. JavaScript is used to do client validation and you can use any .NET language to do server side validation.
I will explain you CustomValidator using server side. You should rely more on server side validation.
To write CustomValidator on server side you override ServerValidate event.
Source Code
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">  
  3. <html xmlns="">  
  4. <head runat="server">  
  5.     <title>Untitled Page</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         <asp:Label ID="Label1" runat="server" Text="User ID:"></asp:Label>  
  11.  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  12.  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   
  13.             ControlToValidate="TextBox1" ErrorMessage="User id required"></asp:RequiredFieldValidator>   
  15.         <asp:CustomValidator ID="CustomValidator1" runat="server" OnServerValidate="UserCustomValidate"  
  16.             ControlToValidate="TextBox1"   
  17.             ErrorMessage="User ID should have atleast a capital, small and digit and should be greater than 5 and less  
  18. than 26 letters"   
  19.             SetFocusOnError="True"></asp:CustomValidator>  
  20.         </div>  
  21.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />  
  22.     </form>  
  23. </body>  
  24. </html>  
Code behind file
  1. using System;  
  2. using System.Configuration;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Security;  
  7. using System.Web.UI;  
  8. using System.Web.UI.HtmlControls;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.WebControls.WebParts;  
  11. using System.Xml.Linq;  
  13. public partial class _Default : System.Web.UI.Page  
  14. {  
  15.     protected void UserCustomValidate(object source, ServerValidateEventArgs args)  
  16.     {  
  17.         string str = args.Value;  
  18.         args.IsValid = false;  
  19.        //checking for input length greater than 6 and less than 25 characters  
  20.         if (str.Length < 6 || str.Length > 25)  
  21.         {  
  22.             return;  
  23.         }  
  24.         //checking for a atleast a single capital letter  
  25.         bool capital = false;  
  26.         foreach (char ch in str)  
  27.         {  
  28.             if (ch >= 'A' && ch <= 'Z')  
  29.             {  
  30.                 capital = true;  
  31.                 break;  
  32.             }  
  33.         }  
  34.         if (!capital)  
  35.         {  
  36.             return;  
  37.         }  
  38.        //checking for a atleast a single lower letter  
  39.         bool lower = false;  
  40.          foreach (char ch in str)  
  41.         {  
  42.             if (ch >= 'a' && ch <= 'z')  
  43.             {  
  44.                 lower = true;  
  45.                 break;  
  46.             }  
  47.         }  
  48.         if (!lower)  
  49.         {  
  50.             return;  
  51.         }  
  52.         bool digit = false;  
  53.         foreach (char ch in str)  
  54.         {  
  55.             if (ch >= '0' && ch <= '9')  
  56.             {  
  57.                 digit = true;  
  58.                 break;  
  59.             }  
  60.         }  
  61.          if (!digit)  
  62.         {  
  63.             return;  
  64.         }  
  65.         args.IsValid = true;  
  66.     }  
  67.     protected void Page_Load(object sender, EventArgs e)  
  68.     {  
  69.     }  
  70.    protected void Button1_Click(object sender, EventArgs e)  
  71.     {  
  72.     }  
  73. }
The server side validation you write does not need to provide the exact same validation as that of the client side validation. The client side validation can check for the user input data for range and type and server side validation can check for matching of data with database. Both server side and client side validation can be used for total solution.
ASP.NET has provided an additional control that complements the validator controls.
The ValidationSummary control is reporting control, which is used by the other validation controls on a page.
You can use this validation control to consolidate errors reporting for all the validation errors that occur on a page instead of leaving this up to each and every individual validation control.
The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list.
  1. <asp:ValidationSummary ID="ValidationSummary1" runat="server"   
  2.         style="top: 390px; left: 44px; position: absolute; height: 38px; width: 625px" />  
Both ErrorMessage and Text properties are used to display error messages. Text error message have precedence.
If you are using ValidationSummary than only ErrorMessage and Text property is used.
The complete code for the above ValidationSummary is as:
Default.aspx Design
Default.aspx Source code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>   
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
  3. "">  
  4. <html xmlns="">  
  5. <head runat="server">  
  6.     <title>Untitled Page</title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <asp:Label ID="Label1" runat="server" Style="top: 239px; left: 75px; position: absolute;  
  12.             height: 22px; width: 128px" Text="Enter your Age:"></asp:Label>  
  14.         <asp:Label ID="Label2" runat="server" Style="top: 94px; left: 81px; position: absolute;  
  15.             height: 22px; width: 128px" Text="Enter your name:"></asp:Label>  
  16.     </div>  
  17.     <asp:TextBox ID="TextBox1" runat="server" Style="top: 95px; left: 250px; position: absolute;  
  18.         height: 22px; width: 128px"></asp:TextBox>  
  19.     <p>  
  20.         <asp:TextBox ID="TextBox4" runat="server" Style="top: 195px; left: 249px; position: absolute;  
  21.             height: 22px; width: 127px"></asp:TextBox>  
  22.     </p>  
  23.     <p>  
  24.         <asp:Label ID="Label3" runat="server" Style="top: 148px; left: 76px; position: absolute;  
  25.             height: 22px; width: 128px" Text="Enter Password:"></asp:Label>  
  26.     </p>  
  27.     <p>  
  28.         <asp:TextBox ID="TextBox3" runat="server" Style="top: 146px; left: 249px; position: absolute;  
  29.             height: 22px; width: 127px" TextMode="Password"></asp:TextBox>  
  30.     </p>  
  31.    <p>  
  32.         <asp:Label ID="Label4" runat="server" Style="top: 197px; left: 75px; position: absolute;  
  33.             height: 22px; width: 128px" Text="Confirm Password:"></asp:Label>  
  34.     </p>  
  35.     <asp:TextBox ID="TextBox2" runat="server" Style="top: 236px; left: 250px; position: absolute;  
  36.         height: 22px; width: 127px" TextMode="Password"></asp:TextBox>  
  37.     <asp:CompareValidator ID="CompareValidator1" runat="server" Style="top: 197px; left: 522px;  
  38.         position: absolute; height: 22px; width: 17px" ErrorMessage="CompareValidator"  
  39.         ControlToCompare="TextBox2" ControlToValidate="TextBox3">*</asp:CompareValidator>  
  40.     <p>  
  41.         <asp:Button ID="Button1" runat="server" Style="top: 333px; left: 248px; position: absolute;  
  42.             height: 26px; width: 56px" Text="Submit" />  
  43.         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Style="top: 196px;  
  44.             left: 393px; position: absolute; height: 22px; width: 22px" ErrorMessage="Confirm Password mandatory & should match password"  
  45.             ControlToValidate="TextBox3">*</asp:RequiredFieldValidator>  
  46.         <asp:RangeValidator ID="RangeValidator1" runat="server" Style="top: 235px; left: 388px;  
  47.             position: absolute; height: 22px; width: 156px; bottom: 288px;" ErrorMessage="age between 18-100"  
  48.             ControlToValidate="TextBox4" MaximumValue="100" MinimumValue="18" Type="Integer">*</asp:RangeValidator>  
  49.         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" Style="top: 92px;  
  50.             left: 393px; position: absolute; height: 22px; width: 156px" ErrorMessage="Name is required"  
  51.             ControlToValidate="TextBox1">*</asp:RequiredFieldValidator>  
  52.         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" Style="top: 146px;  
  53.             left: 391px; position: absolute; height: 22px; width: 156px" ErrorMessage="Password mandatory"  
  54.             ControlToValidate="TextBox2">*</asp:RequiredFieldValidator>  
  55.     </p>  
  56.     <asp:ValidationSummary ID="ValidationSummary1" runat="server" Style="top: 390px;  
  57.         left: 44px; position: absolute; height: 38px; width: 625px" />  
  58.     </form>  
  59. </body>  
  60. </html>  
Output of ValidationSummary program


I hope that this article would have helped you in understanding the Validation Controls in ASP.NET. Please share it if you know more about this article. Your feedback and constructive contributions are welcome.