Validation Controls in ASP.NET using VB.NET

Introduction and Demonstration

ASP.NET removes the hassle of duplicating validation code, a common problem of performing data validation using classic ASP, by neatly encapsulating the standard validations into server controls. You can declaratively relate the validation control to the control whose value needs to be validated, using the ControlToValidate attribute. You can also attach multiple validation controls to a single control. The ASP.NET validation server controls provide server-side validation for all browsers and supply client-side validation via JavaScript for browsers that support JavasScript and DHTML. You can also write your own custom client and/or server-side validation functions, as you'll see in the code example for this section.

One feature that most web programmers would like to have is a summary of the validation errors for the values entered into a page's controls. The ValidationSummary control provides this much-desired feature.

ControlPurpose
CompareValidatorCompares the input in the attached control with a constant value or the property value of another control.
CustomValidatorInvokes custom validation code that you have written.
RangeValidatorChecks if the value is between specified upper and lower limits.
RegularExpressionValidatorChecks if the input matches a pattern defined by a regular expression.
RequiredFieldValidatorEnsures that the user can't skip the required value.
ValidationSummaryShows a summary of errors emitted by all validators in that form.

The simplified syntax of the validation controls is as follows:

<asp:comparevalidator id="cvCompare" controltovalidate="value1" controltocompare="value2"
    operator="equal" type="integer" errormessage="Fields are not equal!" display="dynamic"
    runat="server" />
<asp:customvalidator id="cvDate" controltovalidate="year" errormessage="Not a valid year!"
    onservervalidate="servervalidation" clientvalidationfunction="ClientValidate"
    display="dynamic" runat="server" />
<asp:rangevalidator id="rvCompare" controltovalidate="value" minimumvalue="0" maximumvalue="100"
    type="integer" errormessage="Value not in valid range!" runat="server" />
<asp:regularexpressionvalidator id="reZipCode" controltovalidate="zipcode" validationexpression="^\d{5}$|^\d{5}-\d{4}$"
    errormessage="Not a valid Zip code!" display="static" runat="server"
/>
<asp:requiredfieldvalidator id="rfvLogin" controltovalidate="login" display="static"
    errormessage="Login cannot be blank!" runat="server" />
<asp:validationsummary id="vsSummary" displaymode="bulletlist" headertext="Page has the following errors: "
    showsummary="true" showmessagebox="false" runat="server" />

The controls can then be referenced programmatically with code fragments like:

cvCompare.ControlToCompare = "Value3"
cvDate.ClientValidationFunction="ClientValidateLeapYear"
reZipCode.ValidationExpression="^\d{5}$|^\d{5}$"
rfvLogin.InitialValue = "SomeUser"
vsSummary.DisplayMode = ValidationSummaryDisplayMode.List

Index.aspx Page

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<
head>
    <title>Validation Control Example</title>
    <script language="javascript">
<!--
        function ClientValidate(source, arguments) {
            
//Declare variables.
            var r, re;
           
//Create regular expression object.
            re = new RegExp(/^[1-9][0-9][0-9][0-9]$/);
           
//Test for match.
            r = re.test(arguments.Value);
           
//Return results.
            arguments.IsValid = r;
        }
-->
   
</script>
    <script runat="server">
Sub Page_Load( )
vsSummary.DisplayMode = ValidationSummaryDisplayMode.List
End Sub
Sub ServerValidation (source As object, args _
As ServerValidateEventArgs)
Dim RegExVal As New _
System.Text.RegularExpressions.Regex("^\ d{4}$")
If RegExVal.IsMatch(args.Value) Then
args.IsValid = True
Else
args.IsValid = False
End If
End Sub
    </script
>
</head>
<
body>
    <h1>
        Validation Control Example</h1>
    <form id="Form1" runat="server">
    <asp:Table ID="MyTable" border="1" CellPadding="5" CellSpacing="0" runat="server">
        <asp:TableRow ID="Tablerow1" runat="server">
            <asp:TableCell ID="Tablecell1" runat="server">
Compare Validator Control:
<br><br>
Enter two numbers to compare
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell2" runat="server">
                <asp:TextBox ID="value1" runat="server" /><br>
                <asp:TextBox ID="value2" runat="server" /><br>
                <asp:CompareValidator ID="cvCompare" ControlToValidate="value1" ControlToCompare="value2"
                    Operator="equal" Type="integer" ErrorMessage="Fields are not equal!" Display="dynamic"
                    runat="server" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow2" runat="server">
            <asp:TableCell ID="Tablecell3" runat="server">
CustomValidator Control:
<br><br>
Enter a 4-digit year
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell4" runat="server">
                <asp:TextBox ID="year" runat="server" /><br>
                <asp:CustomValidator ID="cvDate" ControlToValidate="year" ErrorMessage="Not a valid year!"
                    OnServerValidate="servervalidation" ClientValidationFunction="ClientValidate"
                    Display="dynamic" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow3" runat="server">
            <asp:TableCell ID="Tablecell5" runat="server">
RangeValidator Control:
<br><br>
Enter an integer between 0 and 100
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell6" runat="server">
                <asp:TextBox ID="value" runat="server" /><br>
                <asp:RangeValidator ID="rvCompare" ControlToValidate="value" MinimumValue="0" MaximumValue="100"
                    Type="integer" ErrorMessage="Value not in valid range!" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow4" runat="server">
            <asp:TableCell ID="Tablecell7" runat="server">
RegularExpressionValidator Control:
<br><br>
Enter a valid 5 or 9-digit zip code
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell8" runat="server">
                <asp:TextBox ID="zipcode" runat="server" /><br>
                <asp:RegularExpressionValidator ID="reZipCode" ControlToValidate="zipcode" ValidationExpression="^\d{5}$|^\d{5}-\d{4}$"
                    ErrorMessage="Not a valid Zip code!" Display="static" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow5" runat="server">
            <asp:TableCell ID="Tablecell9" runat="server">
RequiredFieldValidator Control:
<br><br>
Enter a login name
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell10" runat="server">
                <asp:TextBox ID="login" runat="server" /><br>
                <asp:RequiredFieldValidator ID="rfvLogin" ControlToValidate="login" Display="static"
                    ErrorMessage="Login cannot be blank!" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow6" runat="server">
            <asp:TableCell ID="Tablecell11" runat="server">
ValidationSummary Control:
            </asp:TableCell
>
            <asp:TableCell ID="Tablecell12" runat="server">
                <asp:ValidationSummary ID="vsSummary" DisplayMode="bulletlist" HeaderText="Page has the following errors: "
                    ShowSummary="true" ShowMessageBox="false" runat="server" />
            </asp:TableCell
>
        </asp:TableRow>
        <asp:TableRow ID="Tablerow7" runat="server">
            <asp:TableCell ID="Tablecell13" colspan="2" runat="server">
                <asp:Button ID="Button1" Text="submit" runat="server" />
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>
    <asp:Label ID="MyLabel" runat="server" />
    </form>
</body>
</
html>

HAVE A HAPPY CODING!