The Compare Validator

Although the ability to ensure the user has made some sort of entry is great, you will often want to validate that the entry content is within certain guidelines. One of the most common requirements for validation is to compare the user’s input to a value constant, the value of another control, or a database value. To do this, you can use a CompareValidator control.

To demonstrate, add to the site a new web page called CompareValidator.aspx. Copy the <body> of ValidationSummary.aspx into it and then add a new row to the main <table> immediately above the row containing the Submit Bug button. This row will contain a TextBox control to specify a page number where the bug was found and two validator controls: a RequiredFieldValidator and a CompareValidator.

   <td>Page Number:</td>
      <asp:TextBox ID="txtNumPurch" runat="server" />
      <asp:RequiredFieldValidator runat="server" ID="rfvPageNumber" 
         ErrorMessage="You did not enter the page number" Text="*" />
      <asp:CompareValidator runat="server" ID="cmpPageNumber"
         ErrorMessage="Invalid page number" Type="Integer"
         Operator="GreaterThan" ValueToCompare="0" Text="*" />
ValidatorCallout controls in action

Figure 11-7. ValidatorCallout controls in action

Both validators are placed into the same cell in the table, and both validators validate the same control: txtPageNumber ...

Get Programming ASP.NET 3.5, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.