Wednesday, August 10, 2016

Validation Controls of ASP.NET

In ASP.NET there are six validation controls. Validation controls are used for
validating User input data. ASP.NET Validation controls work both client side
and server side.

I will explain each validation control with example.

(1) RequiredFieldValidator :

It validates whether data is entered in the control. It can be used with a textbox.
Below example validates textbox named txtName :

HTML Code (.Aspx):

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
&nbsp;
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
   runat="server" ErrorMessage="Enter Name"
    ControlToValidate="txtName" Display="Dynamic">
 </asp:RequiredFieldValidator>

We have to specify the ID of the control to be validated in ControlToValidate
property of the Validator. Display property can be set to Dynamic if we don't 
want to display the space occupied by the validator. In ErrorMessage we can
specify the message to be displayed on error.

I will also show another example of how to use RequiredFieldValidator for a
DropDownList control.

<asp:DropDownList ID="ddlGender" runat="server">
       <asp:ListItem Text="" Value=""></asp:ListItem>
       <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
       <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
 </asp:DropDownList>
&nbsp;
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
   runat="server" ErrorMessage="Select Gender"
    ControlToValidate="ddlGender" Display="Dynamic">
 </asp:RequiredFieldValidator>

It will display error message if no value is selected. 

Suppose DropDownList has initial value For eg: Select
and it has to validate that condition. In that case we can specify 
in InitialValue property of the validator. 
Below you can see that example :

<asp:DropDownList ID="ddlGender" runat="server">
       <asp:ListItem Text="Select" Value="0"></asp:ListItem>
       <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
       <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
 </asp:DropDownList>
&nbsp;
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
   runat="server" ErrorMessage="Select Gender"
    ControlToValidate="ddlGender" Display="Dynamic"  InitialValue="0">
 </asp:RequiredFieldValidator>

(2) RangeValidator :

It validates whether User input is in a specified range which can be specified
in MinimumValue and MaximumValue properties of the Validator.

It can be used for validating six data types, Currency, String, Integer, Double and Date.

Below example shows how to validate Age which has to be fed with values
between 18 and 100.

 <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
&nbsp;
  <asp:RangeValidator ID="RangeValidator1" 
          runat="server" ErrorMessage="Wrong range of Age"
         ControlToValidate="txtAge" Display="Dynamic" Type="Integer"
         MinimumValue="18" MaximumValue="100">
 </asp:RangeValidator>

Below example shows how to validate Date which has to be between
01-01-2016 and 12-31-2016. (MM-DD-yyyy format).

<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
&nbsp;
<asp:RangeValidator ID="RangeValidator2" 
    runat="server" ErrorMessage="Wrong range of date"
    ControlToValidate="txtDate" Display="Dynamic" Type="Date"
    MinimumValue="01-01-2016" MaximumValue="12-31-2016">
</asp:RangeValidator>

(3) RegularExpressionValidator :

This validator can be used to validate whether User input is in a specified format.
ValidationExpression property is used to specify the Regular Expression.

Below example shows how to enter a PinCode which has to be a 6 Digit Number:

 <asp:TextBox ID="txtPin" runat="server"></asp:TextBox>
&nbsp;
  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" 
    runat="server" ErrorMessage="Please enter 6 digit"
    ControlToValidate="txtPin" Display="Dynamic"
    ValidationExpression="^[0-9]{6}$">
  </asp:RegularExpressionValidator>

There are many built in Regular Expression formats available if we choose from
Regular Expression Editor of the Properties Window like Internet Email Address,
Internet URL, U.S Zip Code,etc.

Below I will show one sample of validating Email Address selected via
Regular Expression Editor:

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
&nbsp;
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" 
 runat="server" ErrorMessage="Incorrect Email format"
 ControlToValidate="txtEmail" Display="Dynamic"
 ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
 </asp:RegularExpressionValidator>

(4) CompareValidator :

This validator is used for comparing two values of two controls.

The ID of the control to which value is compared to is provided in 
ControlToCompare property of the validator.

It can be used for validating six data types, Currency, String, Integer, Double and Date.

It has various Comparison operators like DataType Check, Greater than, Less than,Equal,
Greater than Equal, Less than Equal and Not Equal.

Below is an example to validate Greater than of Type Integer.

 <asp:TextBox ID="txtOne" runat="server"></asp:TextBox>
 &nbsp;
 <asp:TextBox ID="txtTwo" runat="server"></asp:TextBox>
 &nbsp;
 <asp:CompareValidator ID="CompareValidator1" 
runat="server" ErrorMessage="Value in first textbox has to be bigger than second one"
ControlToValidate="txtOne" ControlToCompare="txtTwo" Display="Dynamic" 
Operator="GreaterThan" Type="Integer">
</asp:CompareValidator>

CompareValidator can be used for checking Data Type if we didn't provide
ControlToCompare and set Operator to DataTypeCheck.

Below is an example to check Data Type Double using CompareValidator:

<asp:TextBox ID="txtPrice" runat="server"></asp:TextBox>
 &nbsp;
<asp:CompareValidator ID="CompareValidator2" 
 runat="server" ErrorMessage="Incorrect value" Operator="DataTypeCheck"
 ControlToValidate="txtPrice" Display="Dynamic" Type="Double">
  </asp:CompareValidator>

(5) CustomValidator :

With this validator we can write validation logic since it doesn't have pre-defined
way of working like other validators. If none of the other validators work, we can
go for CustomValidator. 

For this validator we can provide Client Side validation function as well as Server Side
Code for validating using the properties ClientValidationFunction and
OnServerValidate.

Below is an example to check that Maximum characters to be entered to the Name
TextBox is less than 100.

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
&nbsp;
<asp:CustomValidator ID="CustomValidator1" 
   runat="server" ErrorMessage="Maximum characters exceeded" 
   ClientValidationFunction="checkLength" 
   OnServerValidate="checkLength_ServerValidate"
   ControlToValidate="txtName" Display="Dynamic">
 </asp:CustomValidator>

Code for ClientValidationFunction is 

HTML Code:

<script type="text/javascript">
        function checkLength(source, args) {
            if (args.Value.length <= 100)
                args.IsValid = true;
            else
                args.IsValid = false;
        }
 </script>

Server Side Code is :

C# Code (.aspx.cs) :

protected void checkLength_ServerValidate(object sender, ServerValidateEventArgs e)
 {
        if (e.Value.Length <=100)
            e.IsValid = true;
        else
            e.IsValid = false;
  }

(6) ValidationSummary :
     
This control provides a summary of all validations of a page in one place. We can
 specify various Display modes using property DisplayMode and three
different modes are BulletList, List and Single Paragraph.

Below is the sample :
 <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

Output is like this :


No comments:

Post a Comment