Validation Controls In ASP.Net

Validation Controls allow you to validate user entry on WebForms. These controls can be very handy tools. Unexpected values can cause the webpage to blow up and result in an error page. It is still possible to add the validation within the code. Validation control provides an easy and object - oriented approach for the same task without sacrificing clarity of the code. These controls help in avoiding some negative user experience.

Types of Validation Controls and Common Properties of Validation Controls

You will typically need to set the following properties for validation controls
ControlToValidate : The name of the control to be validated
Text : This text is displayed for the control, typically indicated by * or a hint about the validation
ErrorMessage : This is the message that will displayed if validation fail for that validation control.
The followings are the different types of validation controls and examples for each item.  If you use Visual Studio.Net as your editor, you can drag and drop the desired validation control from the toolbox. You can use any combination of validation controls on a single web control.  

1.  RequiredFieldValidator Control

This will be most commonly needed validation control, This control make a field mandatory
Eg:

<script language ="C#" runat="server">
     void Hibtn_Click(Object Scr, EventArgs E)
    {
        lblHello.Text = "Hi" + txtName.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Required Validator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />
    <asp:RequiredFieldValidator ID ="RequiredFieldValidator" runat ="server"  
    ControlToValidate ="txtName"
    ErrorMessage = "Name is a Required field"
    ForeColor="Red" >
    </asp:RequiredFieldValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>



2.  CompareValidator Control

Mainly 3 types are there
a. Compare User entity against a data type
Specify the data to be compared by setting the Type property of the CompareValidator control using the ValidationDataType enumeration values ( Currency, DateTime, Double, Integer, String)

Eg:

<script Language ="C#" runat="server">
    void Hibtn_Click(Object Scr, EventArgs E)
    {
        lblHello.Text = "Hi" + txtName.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Compare Validator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    Enter Your Age: <asp:TextBox ID="txtAgeYrs" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />

    <asp:CompareValidator ID="CompareFieldValidator1" runat="server"
     ForeColor="Red" ControlToValidate ="txtAgeYrs"
     Type= "Integer"
     Operator="DataTypeCheck"
     ErrorMessage="Please Enter an Integer">
     </asp:CompareValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>


b.  Compare the User entry against a constant value
Specify the constant value to be compared against by setting ValueToCompare property, set the Type Property using the ValidationDataType enumeration, Set the Operator property using the ValidationCompareOperator enumeration( Equal, NotEqual, GreaterThan etc.)
Eg:

<script Language ="C#" runat="server">
    void Hibtn_Click(Object Scr, EventArgs E)
    {
        lblHello.Text = "Hi" + txtName.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Compare Validator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    Enter Your Age: <asp:TextBox ID="txtAgeYrs" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />

    <asp:CompareValidator ID="CompareFieldValidator2" runat="server"
     ForeColor="Red" ControlToValidate ="txtAgeYrs"
     ValueToCompare =0
     Type= "Integer"
     Operator="GreaterThan"
     ErrorMessage="Please Enter a Whole Number greater than Zero">
     </asp:CompareValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>


c. Compare the User entry against value of another control
Specify the control to be compared against using the ControlToCompare Property, Set the Type using ValidationData Type enumeration and Set the Operator property using the ValidationCompareOperator property.
Eg:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Compare Validator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    <br />
    Enter Your email id: <asp:TextBox ID="txtEmail" runat ="server" /><br />
    Re-Enter Your email id: <asp:TextBox ID="txtEmail1" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />
    
     <asp:CompareValidator ID="CompareFieldValidator3" runat="server"
     ForeColor="Red"
     ControlToValidate ="txtEmail"
     ControlToCompare ="txtEmail1"
     Type= "String"
     Operator="Equal"
     ErrorMessage="Please check email Address">
     </asp:CompareValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>


3. RangeValidator Control

As the name indicates this control is used to validate that the used entry fall within a specified range. As with CompareValidator control, the validation can be against specific values or against values of the control.
The minimum value of the range is indicated by setting the MinimumValue or MinimumControl property. Similarly maximum value is indicated by setting the MaximunValue or MaximumControl property. Set the Type using ValidationData Type enumeration.
Eg:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Range Validator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    <br />
    Enter Number Between 1-5 :<asp:TextBox ID="txtNum" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />
     <asp:RangeValidator ID="RangeValidator" runat ="server"
      ForeColor="Red"
      ControlToValidate="txtNum"  
      MinimumValue=1 MaximumValue=5 Type="Integer"
      ErrorMessage="Please Enter and Integer between 1 to 5">
       </asp:RangeValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>


4. RegularExpression Validator Control

This is customized validation control that validate the user entry matches a predefined pattern such as Phone number, Email address etc
Visual Studio.Net provides some predefined patterns. Of course, you can specify your own expressions. Set the pattern to compare by setting the validation expression property.
Eg:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> Regular Expression Validator</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    <br />
    Enter Email Id: <asp:TextBox ID="txtemail" runat ="server" />
    <asp:Button Text="Hi" OnClick ="HiBtn_Click" runat="server" />
    <asp:RegularExpressionValidator ID="RegExpValidator1" runat ="server"
    ErrorMessage="Please Enter a Valid Emailid" ControlToValidate="txtemail"
    ValidationExpression ="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
     </asp:RegularExpressionValidator>
     <asp:RangeValidator ID="RangeValidator" runat ="server"
      ForeColor="Red"
      ControlToValidate="txtNum"  
      MinimumValue=1 MaximumValue=5 Type="Integer"
      ErrorMessage="Please Enter and Integer between 1 to 5">
       </asp:RangeValidator>
    <br />
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>



5. CustomValidator Control

Validation Requirements do not always fall into explict patterns and can become complicated for even medium sized systems. The Custom Validator control is used to validate against any custom validation function created by you.
Eg:

<script language ="C#" runat="server">
     protected void LikeValidate(Object source, ServerValidateEventArgs args)
     {
        try
        {
            string str = Convert.ToString(args.Value);
            args.IsValid =(str!="Yes")?false:true;
        }
         catch
         {
             args.IsValid=false;
        }
     }
    void Hibtn_Click(Object Scr, EventArgs E)
    {
        lblHello.Text = "Hi" + txtName.Text;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CustomValidator Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <br/>
    Enter Your Name: <asp:TextBox ID="txtName" runat ="server" />
    <br />
    Do You like Validation Control: <asp:TextBox ID="txtLike" runat ="server" />
    <asp:Button ID="Button1" Text="Hi" OnClick ="HiBtn_Click" runat="server" />
    <asp:CustomValidator ID="Customvalidator1" runat ="server"
    ControlToValidate ="txtLike"
    ErrorMessage="You must enter Yes"
    OnServerValidate="LikeValidate">
    </asp:CustomValidator>      
    <br />
    <b><asp:Label ID="lblHello" runat="server" /> </b>  
    </form>
</body>
</html>


By Anoop S   Popularity  (4188 Views)