• Validation Controls ASP.NET — PART 2

    Posted on May 5, 2012 by in ASP.NET, Dotnet, VB.NET

    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. In my previous article “Validation Controls in ASP.NET — PART 1”, I have discussed about RequiredFieldValidator, RangeFieldValidator & CompareValidator. In this article, I will explain the rest of them (Custom Validator, RegularExpression Validator) and a ValidationSummaryControl.

    Working With CustomValidator
    The CustomValidator control calls a user-defined function to perform validations that the standard validators can’t handle. The custom function can execute on the server or in client-side script such as Jscript or VBScript. For client-side custom validation, the name of the custom function must be identified in the ClientValidationFunction property. The custom function must have the form funtion myvalidator(source, arguments). Note that the source is the client-side CustomValidator object and arguments is an object with two properties, Value and IsValid. The Value property is the value to be validated and the IsValid property is a Boolean used to set the return result of the validation. For server-side custom validation, place your custom validation in the validator’s OnServerValidate delegate. The following example illustrates using the CustomValidator control using ServerSide Validation.

    <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 = "Page is valid!"
            Else
                lblOutput.Text = "Page is not valid!"
            End If
        End Sub
        Protected Sub OnServerValidate(ByVal sender As Object, _
                             ByVal e As ServerValidateEventArgs)
            Dim num As Integer = Convert.ToInt32(e.Value)
            If num Mod 2 = 0 Then
                e.IsValid = True
            Else
                e.IsValid = False
            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">CustomFieldValidator Example</font></h3>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblOutput" runat="server" Text="Enter an even number:"
                Font-Name="Verdana" Font-Size="10pt"><br /></asp:Label>
        <p>
        <asp:TextBox ID="txtNumber" runat="server"/>&nbsp;&nbsp;
        <asp:CustomValidator ID="CustomValidator1"
                ControlToValidate="txtNumber" OnServerValidate="OnServerValidate"
                Display="Static" Font-Name="Verdana" Font-Size="10pt"
                runat="server">Not an even number!
        </asp:CustomValidator>
        </p>
        <asp:Button ID="btnValidate" runat="server" Text="Validate"
                        OnClick="Validate_Click"/>
    </div>
    </form>
    </body>
    </html>
    

    validation controls asp.net 1

    Enter an odd number in the textbox and hit on “Validate” button. The custom validation function “OnServerValidate” would be triggered on the server and performs the validation.
    validation controls asp.net 2

    Working with RegularExpression Validator
    The RegularExpressionValidator control confirms that the entry matches a pattern defined bya regular expression. This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes and so on.

    RegularExpressionValidator used two key properties to peform its validation: ControlToValidate contains the value to validate and ValidationExpression contains the regular expression to match. The following sample illustrates using the RegularExpressionValidator control.

    <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 = "Page is valid!"
            Else
                lblOutput.Text = "Page is 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">RegularExpressionValidator Example</font></h3>
    <form id="form1" runat="server">
    <div>
        <table bgcolor="#eeeeee" cellpadding="10">
            <tr valign="top">
            <td colspan="3">
                <asp:Label ID="lblOutput" runat="server"
                    Text="Enter a 5 digit zipcode:"
                    Font-Name="Verdana" Font-Size="10pt"/>
            </td>
            </tr>
            <tr valign="top">
            <td colspan="3">
                <font face="Verdana" size="2"><b>Personal Information</b></font>
            </td>
            </tr>
            <tr valign="top">
            <td align="right">
                <font face="Verdana" size="2">Zip Code:</font>
            </td>
            <td>
                <asp:TextBox ID="txtZipCode" runat="server"/>&nbsp;&nbsp;
            </td>
            <td>
                <asp:RegularExpressionValidator ID="rexValidator"
                    ControlToValidate="txtZipCode" ValidationExpression="^\d(5)$"
                    Display="Static" Font-Name="Verdana" Font-Size="10pt"
                    runat="server">
                        Zip code must be 5 numeric digits
                </asp:RegularExpressionValidator>
            </td>
            </tr>
        </table>
        <br />
        <asp:Button ID="btnValidate" runat="server" Text="Validate"
                        OnClick="Validate_Click"/>
    </div>
    </form>
    </body>
    </html>
    

    validation controls asp.net 3
    Enter an invalid zip code and hit “Validate”. The value will get matched agains the regular expression specified in the validator. If it fails, page is rendered invalid and error message displayed.
    validation controls asp.net 4

    How Do I… Use common Regular Expressions ?
     There are variety of tasks that regular expressions can be used in regards to input validation and file parsing. Some of the most common expressions are often hard to remember because of the power and options available. Here is the list of commonly used regular expressions.

    Use Expression
    Social Security Number \d{3}-\d{2}-\d{4}
    US Phone Number ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
    US Postal Code \d{5}(-\d{4})?
    Internet Email Address [\w-][email protected]([\w-]+\.)+[\w-]+
    Internet URL http://([\w-]\.)+[\w-](/[\w- ./?%=]*)?
    Simple Password (digit) ^(?=.*\d).{4,8}$
    Advanced Password (upper, lower, digit) ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$
    Common File Masks ^(.+)\\(.+)\.(.+)
    Major Credit Card \d{4}-?\d{4}-?\d{4}-?\d{4}

    Working with Validation Summary
    When the user’s input is processed(for example, when the form is submitted), the Web Forms framework passes the user’s entry to the associated validation control or controls. The validation controls test the user’s input and set a property to indicate whether the entry passed the validation test. After all validation controls have been processed, the IsValid property on the page is set; if any of the controls shows that a validation check failed, the entire page is set to invalid.

    A ValidationSummary control is displayed when the IsValid property of the page is false. It “polls” each of the validation controls on the page and aggregates the text messages exposed by each. The following example illustrated displaying errors with a ValidationSummary.

    In this example, we are going to create a input form to collect credit card information. I have created input fields for Card Type (DropDownList), Card Expiration Date (DropdownList) & Card Number (text field). These are all required fields. I have 3 required field validators, each corresponding to each input field.  Clicking on the “Validate” button would trigger validation and if the validation fails, page is set to invalid and all the errors messages will be written to “ValidationSummary” control. You can change the layout of the messages in summary control by selecting available options from list format dropdownlist.

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <script runat="server">
        Protected Sub ListFormat_SelectIndexChanged(ByVal sender As Object, _
                                                    ByVal e As EventArgs)
            'change display mode of the validation summary when new option
            'is selected from the listformat dropdownlist
            valSummary.DisplayMode = lstFormat.SelectedIndex
        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">ValidationSummary Example</font></h3>
    <form id="form1" runat="server">
    <div>
        <font face="verdana" size="-1">Select the type of the validation
                        summary display you wish</font>
        <asp:DropDownList ID="lstFormat" runat="server" AutoPostBack="true"
                        OnSelectedIndexChanged="ListFormat_SelectIndexChanged">
            <asp:ListItem>List</asp:ListItem>
            <asp:ListItem>BulletedList</asp:ListItem>
            <asp:ListItem>Single Paragraph</asp:ListItem>
        </asp:DropDownList>
        <table bgcolor="#eeeeee" cellpadding="10">
            <tr><td colspan="3">
                <font face="Verdana" size="2"><b>Credit Card
                          Information</b></font>
                <asp:Label ID="lblOutput" runat="server"
                            Text="Enter a 5 digit zipcode:"
                		Font-Name="Verdana" Font-Size="10pt"/>
            </td></tr>
            <tr><td align="right">
                <font face="Verdana" size="2">Card Type:</font>
            </td>
            <td><asp:RadioButtonList ID="rblCardTypes"
                            RepeatLayout="Flow" runat="server">
                    <asp:ListItem>MasterCard</asp:ListItem>
                    <asp:ListItem>Visa</asp:ListItem>
                </asp:RadioButtonList>
            </td>
            <td><asp:RequiredFieldValidator ID="rfdValidator"
                    ControlToValidate="rblCardTypes"
                    ErrorMessage="Card Type" Width="100%"
                    Display="Static" Font-Name="Verdana" Font-Size="10pt"
                    runat="server>*
                </asp:RequiredFieldValidator>
            </td></tr>
            <tr><td><font face="Verdana" size="2">Card Number:</font></td>
            <td><asp:TextBox ID="txtCardNumber" runat="server</td>
            <td>
                <asp:RequiredFieldValidator ID="rfvValidator2"
                    ControlToValidate="txtCardNumber"
                    ErrorMessage="Card Number." Width="100%"
                    Display="Static" Font-Name="Verdana" Font-Size="10pt"
                    runat="server>*
                </asp:RequiredFieldValidator>
            </td></tr>
            <tr>
      <td><font face="Verdana" size="2">Expiration Date:</font></td>
            <td>
                <asp:DropDownList ID="ddlEpirationDates" runat="server">
                    <asp:ListItem></asp:ListItem>
                    <asp:ListItem>06/12</asp:ListItem>
                    <asp:ListItem>07/12</asp:ListItem>
                    <asp:ListItem>08/12</asp:ListItem>
                </asp:DropDownList>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="rfvValidator3"
                    ControlToValidate="ddlEpirationDates"
                    ErrorMessage="Expiration Date." Width="100%"
                    Display="Static" Font-Name="Verdana" Font-Size="10pt"
                    InitialValue=""
                    runat="server">
                        *
                </asp:RequiredFieldValidator>
            </td>
            </tr>
            <tr>
            <td></td>
            <td>
    <asp:Button ID="btnValidate" runat="server" Text="Validate"/>
            </td>
            <td></td>
            </tr>
        </table>
        <table cellpadding="20">
        <tr><td>
        <asp:ValidationSummary ID="valSummary" runat="server"
                HeaderText="You must enter a value in the following fields:"
                Font-Names="verdana" Font-Size="12" />
        </td></tr></table>
    </div>
    </form>
    </body>
    </html>
    

    validation controls asp.net 5

    Select “BulletedList” from the format list. Do not enter inti any fields and click on “Validate” button. You would notice that all our validation messages displayed in the summary control.
    validation controls asp.net 6

    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