• Validation Controls in ASP.NET — PART 1

    Posted on May 4, 2012 by in ASP.NET, Dotnet, VB.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. A validation control does exactly that. If the data does not pass validation, it will display an error message to the user.

    Working With RequiredFieldValidator
    The RequiredFieldValidator control ensures that the user does not skip an entry. If the user inputs any value into the field identified by ControlToValidate, it is valid. If all the fields in the page are valid, the page is valid. The following sample illustrates using the RequiredFieldValidator.

    <html xmlns="http://www.w3.org/1999/xhtml" >
        <head runat="server"><title>ASP.NET WEBCONTROLS</title>
        <link type="text/css" rel="Stylesheet" href="../Styles.css" />
        </head>
    <body>
        <h3><font face="Verdana">RequiredFieldValidator Example</font></h3>
        <form id="form1" runat="server">
        <div>
            Name: <asp:TextBox ID="tbxTest" runat="server"/>
            <asp:RequiredFieldValidator ID="rfvValid" ControlToValidate="tbxTest"
                            Font-Names="Arial" Font-Size="11" runat="server">
                Required Field!
            </asp:RequiredFieldValidator>
            <p><asp:Button ID="btnTest" runat="server" Text="Enter" /></p>
        </div>
        </form>
    </body>
    </html>
    


    In this example we are using RequiredFieldValidator control to make the “txtTest” textbox a required field. Try clicking on the “Enter” button without entering anything in the name text field.  You would get an “Required Field!” error prompting user to enter something in the name field.

    Working with RangeValidator
    The RangeValidator control tests whether an input value falls within a given range. RangeValidator uses three key properties to perform its validation. ControlToValidate contains the value to validate, MinimumValue defines the minimum value of the valid range, and MaximumValue defines the maximum value of the valid range. These constants are stored as string values, but are converted to the datatype dfined by Type when the comparison is performed.

    I have create two text fields txtComp1 & txtComp2. I have created couple of range validators rangeValInteger & rangeValDate. rangeValInteger would validate value entered in txtComp1 is of type Integer and also if the value is  between 1 and 10. rangeValDate would validate value entered in txtComp2 is of type Date and also if the value is  between 1/1/2010 and 1/1/2012. I have disabled client side validation by setting EnableClientScript propery to false. When the user clicks on Validate button,we explicity call Validate method on the validators to enforce validation. If the validation fails, we print validation fail or success message to the lblOutPut label.

    <html xmlns="http://www.w3.org/1999/xhtml" >
        <script runat="server">
            Protected Sub Validate_Click(ByVal sender As Object, _
    ByVal e As EventArgs)
                rangeValInteger.Validate()
                If rangeValInteger.IsValid Then
                    lblOutput1.Text = "Result: Valid!"
                Else
                    lblOutput1.Text = "Result: Not Valid!"
                End If
                rangeValDate.Validate()
                If rangeValDate.IsValid Then
                    lblOutput1.Text = "Result: Valid!"
                Else
                    lblOutput1.Text = "Result: Not Valid!"
                End If
                If Page.IsValid Then
                    lblOutput1.Text = "Result: Valid!"
                Else
                    lblOutput1.Text = "Result: Not Valid!"
                End If
            End Sub
        </script>
        <head runat="server"><title>ASP.NET WEBCONTROLS</title>
        <link type="text/css" rel="Stylesheet" href="../Styles.css" />
        </head>
    <body>
        <h3><font face="Verdana">RangeFieldValidator Example</font></h3>
        <form id="form1" runat="server">
        <div>
            <table bgcolor="#eeeeee" cellpadding="10">
                <tr valign="top">
                    <td>
                    <h5><font face="verdana">Value to Check:</font></h5>
                    <asp:TextBox ID="txtComp1" runat="server"></asp:TextBox>
                    </td>
                    <td>
                    <h5><font face="verdana">Data Type:Integer
    Min(1),Max(10)</font></h5>
                    </td>
                    <td>
                     <asp:Label ID="lblOutput1" Font-Names="verdana" Font-
    Size="10pt" runat="server" />
                    </td>
                </tr>
                 <tr valign="top">
                    <td>
                    <h5><font face="verdana">Value to Check:</font></h5>
                    <asp:TextBox ID="txtComp2" runat="server"></asp:TextBox>
                    </td>
                    <td>
                    <h5><font face="verdana">Data Type:Date
    Min(1/1/2010),Max(1/1/2012)</font></h5>
                    </td>
                    <td>
                     <asp:Label ID="lblOutput2" Font-Names="verdana" Font-
    Size="10pt" runat="server" />
                    </td>
                </tr>
            </table>
            <p><asp:Button ID="btnValidate" runat="server" Text="Validate"
                            OnClick="Validate_Click"/>
            <asp:RangeValidator ID="rangeValInteger" Type="Integer"
                    EnableClientScript="false"
                    ControlToValidate="txtComp1" MaximumValue="10"
                    MinimumValue="1" runat="server"/>
            <asp:RangeValidator ID="rangeValDate" Type="Date"
                    EnableClientScript="false"
                    ControlToValidate="txtComp2" MaximumValue="1/1/2012"
                    MinimumValue="1/1/2010" runat="server" />
            </p>
            <asp:Label ID="lblOutput" Font-Names="verdana"
                        Font-Size="10pt" runat="server"/>
        </div>
        </form>
    </body>
    </html>
    


    Enter 0 in the first text field and 1/1/1999 in the second text field. Click on “Validate” button and you would notice  that our validators would kick in and make the page invalid.

    Working with CompareValidator:
    The comparevalidator control compares the value of one control to another or to explicit value in the control’s ValueToCompare property. CompareValidator suses three key properties to perform its validation. ControlToValidate and ControlToCompare contain the values to compare. Operator defines the type of comparison to perform, for example, Equal or Not Equal. CompareValidator performs the validation by evaluating these  properties as an expression, as shown in the following example. If the expression evaluates true, the validation result is valid. The following sample illustrates using the CompareValidator control.

    I have create two text fields txtComp1 & txtComp2. I have created a compare validator compareValidator to compare values entered in txtComp1 and txtCompare2 using operator specified in lstOperator list.I have disabled client side validation by setting EnableClientScript propery to false. When the user clicks on Validate button,we explicity call Validate method on the validator to  compare both inputs. If the validation fails, we print validation fail or success message to the lblOutPut label.

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <script runat="server">
        Protected Sub Validate_Click(ByVal sender As Object, ByVal e As EventArgs)
            If Page.IsValid Then
                lblOutput.Text = "Result: Valid!"
            Else
                lblOutput.Text = "Result: Not Valid!"
            End If
        End Sub
        Protected Sub SelecIndexChanged(ByVal sender As Object, _
    ByVal e As EventArgs)
            compareValidator.Operator = lstOperator.SelectedIndex
            compareValidator.Validate()
        End Sub
    </script>
    <head runat="server"><title>ASP.NET WEBCONTROLS</title>
    <link type="text/css" rel="Stylesheet" href="../Styles.css" />
    </head>
    <body>
    <h3><font face="Verdana">CompareFieldValidator Example</font></h3>
    <p>Type a value in each textbox, select a comparison operator, then
        click "Validate" to test</p>
    <form id="form1" runat="server">
    <div>
        <table bgcolor="#eeeeee" cellpadding="10">
            <tr valign="top">
                <td>
                <h5><font face="verdana">String 1:</font></h5>
                <asp:TextBox ID="txtComp1" runat="server"></asp:TextBox>
                </td>
                <td>
                <h5><font face="verdana">Comparison Operator:</font></h5>
                <asp:ListBox ID="lstOperator"
                                OnSelectedIndexChanged="SelecIndexChanged"
                                runat="server">
                    <asp:ListItem Value="Equal" Selected="True">Equal
    </asp:ListItem>
                    <asp:ListItem Value="NotEqual">NotEqual</asp:ListItem>
                    <asp:ListItem Value="GreaterThan">GreaterThan</asp:ListItem>
                    <asp:ListItem Value="GreaterThanEqual"> GreaterThanEqual
    </asp:ListItem>
                    <asp:ListItem Value="LessThan">LessThan</asp:ListItem>
                    <asp:ListItem Value="LessThanEqual">LessThanEqual
    </asp:ListItem>
                </asp:ListBox>
                </td>
                <td>
                <h5><font face="verdana">String 2:</font></h5>
                <asp:TextBox ID="txtComp2" runat="server"></asp:TextBox>
                </td>
            </tr>
        </table>
        <p><asp:Button ID="btnValidate" runat="server" Text="Validate"
                        OnClick="Validate_Click"/>
        <asp:CompareValidator ID="compareValidator" Type="String"
                EnableClientScript="false"
                ControlToValidate="txtComp1" ControlToCompare="txtComp2"
                runat="server"/>
        </p>
        <asp:Label ID="lblOutput" runat="server"></asp:Label>
    </div>
    </form>
    </body>
    </html>
    


    Enter “test” in “String 1” field and “test” in “String 2” input field. Select “Equal” from the operator dropdownlist. Click on “Validate” and you would notice that the validation goes through.

    Enter “test1” in String 1 field and “test” in “String 2” input field. Select “Equal” from the operator dropdownlist. Click on “Validate” and you would notice that the validation fails.

    Be Sociable, Share!
      Post Tagged with ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    Leave a Reply