Validation Controls in ASP.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.

Control
Purpose
CompareValidator
Compares the input in the attached control with a constant value or the property value of another control.
CustomValidator
Invokes custom validation code that you have written.
RangeValidator
Checks if the value is between specified upper and lower limits.
RegularExpressionValidator
Checks if the input matches a pattern defined by a regular expression.
RequiredFieldValidator
Ensures that the user can't skip the required value.
ValidationSummary
Shows 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" %>
<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 runat="server">
      <asp:table id="MyTable"
         border="1"
         cellpadding="5"
         cellspacing="0"
         runat="server">
         <asp:tablerow runat="server">
            <asp:tablecell runat="server">
               Compare Validator Control:
               <br><br>
               Enter two numbers to compare
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell runat="server">
               CustomValidator Control:
               <br><br>
               Enter a 4-digit year
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell runat="server">
               RangeValidator Control:
               <br><br>
               Enter an integer between 0 and 100
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell runat="server">
               RegularExpressionValidator Control:
               <br><br>
               Enter a valid 5 or 9-digit zip code
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell runat="server">
               RequiredFieldValidator Control:
               <br><br>
               Enter a login name
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell runat="server">
               ValidationSummary Control:
            </asp:tablecell>
            <asp:tablecell 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 runat="server">
            <asp:tablecell colspan="2" runat="server">
               <asp:button text="submit" runat="server"/>
            </asp:tablecell>
         </asp:tablerow>
      </asp:table>
      <asp:label id="MyLabel" runat="server"/>
   </form>
</body>
</html>


Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples