O'Reilly logo

Programming ASP.NET, 3rd Edition by Dan Hurwitz, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required