ASP.NET Validation Controls

Introduction to ASP.net Validation Controls

  • Validation is an important concept to get a correct output as the user gives the input to web form must be in proper format then only the server will result in meaningful output.
  • Data entered by the user must perform validation before sending to the server for processing.

Definition

“Validation is checking whether the user has entered correct data or input or not and then process the request and send it to the server for output.”

ASP.NET Validation Controls

Note

Validation can be performed at the client-side as well as server-side.

  • Client-side validation makes the process fast as there is less number of hits to the server.
  •  Server-side validation is used to remove the limitation of client browsers dependencies and scripting language support. 

Types of Validation

Validation can be classified into two types based on client and server validation:

  1. Client side Validation
  2. Server side Validation
ASP.NET Validation Controls 1
  1. Client side Validation
  • Validations performed  at Client-Side i.e., browser.
  • User gets information immediately as validation performed before a request is sent to the server. 

2.  Server-side Validation

  • Server-side validation takes place before data processing in the database.
  • This type of validation is used, where client browser dependencies are involved.

Hierarchy Model of ASP.NET Validation controls

  • All the ASP.NET Validation controls derive from the WebControl class.
  • The WebControl class derive from System.Web.UI.Control, which itself derives from System.Object
ASP.NET Validation Controls 2
  • ASP.NET validation controls are derived from the abstract class i.e., BaseValidator Class, which is derived from Label Control class.

BaseValidator Class

BaseValidator class is parent for all ASP.NET validation controls.

It is abstract class means we cannot directly instantiate BaseValidator.

All ASP.NET Validation controls inherit methods and properties of BaseValidator class.

Some common and essential properties provided by the BaseValidator Control class are as follows:

Properties Description
ControlToValidate Which control to be validate.
Display A Mode in which error message is shown like static, dynamic, none.
ErrorMessage Error message to be displayed.
Text If validation fails, the message to be shown.
SetFocusOnError Focus is set to the control having incorrect values

Note

  • Property named ControlToValidate cannot be left blank.
  • Multiple validation controls can be assigned to a webform input control.
  • CauseValidation property of the control must be “true” only then server validation will take place.

Validation Controls used in ASP.NET

The Validation controls used in APS.NET Web Form are as follows:

  1. ValidationSummary
  2. RequiredFieldValidator
  3. RangeValidator
  4. CompareValidator
  5. RegularExpressionValidator
  6. CustomValidator

Validation Controls can be used at the client-side as well as server-side.

  1. ValidationSummary Control :
  2. ValidationSummary Control is used tosummarize all the error message at one place in the list, bullet, or single message form.
  3. Some important properties of ValidationSummary Control are DisplayMode, ShowMessageBox, ShowSummary,
  4. RequiredFieldValidator Control:
  • Control used to make web form input control required i.e. it cannot be left empty.
  • User will have to enter some input without which form will not be transferred to the server.

Code for aspx page

<h1>ASP.NET Validation Controls</h1>
 <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
 <p>
  First Name :
 <asp:TextBox ID="txtFirstName" runat="server" CausesValidation="True">
 </asp:TextBox>
 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"         ErrorMessage="Please Provide First Name"  ControlToValidate="txtFirstName"> Required
</asp:RequiredFieldValidator>
</p>
<p>
Last Name:
 <asp:TextBox ID="txtLastName" runat="server">
 </asp:TextBox>
 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Provide Last Name" ControlToValidate="txtLastName"> Required
 </asp:RequiredFieldValidator>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" />
</p> 
ASP.NET Validation Controls 3

Note

InitialValue : The property of RequiredFieldValidation control will check in the associated control to validate whether the value is same as InitialValue or not. If a value matches to IntitalValue, it is invalid, value other than InitialValue is Valid.

  • RangeValidator Control
  • RangeValidator Control is used to apply some upper and lower limit for associated input control.
  • Value in input control is checked with Maximum and Minimum property values.
  • Type property of RangeValidator Control defines which type of comparison takes place.
 <tr>
       <td style="height: 25px">Age:</td>
       <td style="height: 25px">
                   <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                         <asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="Age must be      between 18 and 50 " ControlToValidate="txtAge" MaximumValue="50" MinimumValue="18"   Type="Integer">
                          </asp:RangeValidator>
           </td>
  </tr> 
ASP.NET Validation Controls 4
  • CompareValidator Control
  • CompareValidator is used to compare some value of control with some constant value or any value within different control.
  • When we have to compare the value of one input control to others, we need to provide value for CotrolToCompare property.
  • If the value is to be compared with some constant, ValueToCompare must be given.

Some important properties of CompareValidator are ControlToCompare , ControlToValidate , Type , Operator ,Display etc.

 <tr>
 <td>Password:</td>
 <td>
 <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
 </td>
 </tr>
  <tr>
 <td style="height: 25px">Confirm Password:</td>
 <td style="height: 25px">
 <asp:TextBox ID="txtConfirmtxtPassword" runat="server">
 </asp:TextBox>
  
                         <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Please ensure the password and confirm password is same" ControlToValidate="txtConfirmtxtPassword" ControlToCompare="txtPassword">*
 </asp:CompareValidator>
             </td>
 </tr> 
ASP.NET Validation Controls 5
  • RegularExpressionValidator Control
  • RegularExpression Validator is used when the input from the user is in a standard pattern, and that pattern must be followed to prevent wrong entry to the database.
  • The pattern specified in ValidationExpression property is validated then only process proceeds.
 <tr>
             <td>Email ID
 </td>
             <td>
             <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
             <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" runat="server" ErrorMessage="Please enter valid email" ControlToValidate="txtEmail">
 </asp:RegularExpressionValidator>
 </td>
 </tr> 

Frequently used Currency formats:

To validate a positive currency. Example(1.00)  \d+(\.\d\d)?$
To validate a positive or negative currency. Example (1.20) ^(-)?\d+(\.\d\d)?$


Frequently used string formats:

To validate only characters ^[a-zA-Z]*$
To validate character or numbers and character only, not space, not special character. Example :-Rajpal123 ^[a-zA-Z0-9]*$
To validate min 8 and max 20 character with spaces. Example :-  ram 234 ([a-zA-Z0-9\s]){8,20} 


Frequently used Number Formats:

To validate Float number with + Or – Symbol. Example 1.222 Or -1.222 ^[-+]?[0-9]*\.?[0-9]*$
To validate user can input only number but no limit. Example :- 125465896 ^(\d+)?$
To validate only three digit. Example:- 123 ^(\d\d\d)?$




Some File uploader Regular expression Formats:

To validate format for file uploading Example:- abc.jpg

^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.gif|.GIF|.jpg|.JPG|.jpeg|.JPEG)$


5.  CustomValidator Control

CustomValidator is used when the validation is performed to match the user’s defined standards.

CustomValidator allows you to perform validation from both the client-side as well as server-side.

 <tr>
                 <td>Message</td>
                 <td>
                     <asp:TextBox ID="txtMessage" runat="server"></asp:TextBox>
                     <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Text must be exactly 10 characters long!" ControlToValidate="txtMessage" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
                 </td>
             </tr>
 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
         {
             if (args.Value.Length == 10)
                 args.IsValid = true;
             else
                 args.IsValid = false;
         } 
ASP.NET Validation Controls 7