The Compare Validator

While the ability to ensure that 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 see this at work, make a new copy of the RequiredValidationSummary protect and name the new web site CompareValidator. Add a new control that asks the user how many copies of the book he has purchased.

To do so, you will insert a text box, a required field validator, and a compare validator into a new row before the row for the Display Errors drop-down:

<tr>
    <td>Number purchased:</td>
    <td><ASP:TextBox id="txtNumPurch" runat=server width="50px" /></td>
    <td>
        <asp:RequiredFieldValidator runat="server"
           id="RequiredFieldValidatorNumPurch"

           ControlToValidate="txtNumPurch"
           SetFocusOnError=true
           ErrorMessage ="You did not enter the number purchased"
           Width="100%" >*
        </asp:RequiredFieldValidator>

        <asp:CompareValidator runat="server"
           id="CompareValidatorNumPurch"

           ControlToValidate="txtNumPurch"
           SetFocusOnError=true
           ErrorMessage ="Invalid number purchased"
           Type="Integer"
           Operator="GreaterThan"
           ValueToCompare=0>*</asp:CompareValidator>
    </td>
</tr>

Both validators are placed into the same cell in the table, and both validators validate the same control: txtNumPurch. The required field validator is needed because the compare validator will always return true ...

Get Programming ASP.NET, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.