The Compare Validator
While ensuring that the user has made an entry is very useful, you will often want to validate that the content of the entry is within certain guidelines. One of the most common requirements for validation is to compare the user’s input to a constant, the value of another control, or a database value.
For instance, to continue the example web page, you can add a new control to your bug reporting dialog that will ask the user how many copies of the book he purchased. The following code should be inserted immediately before the HTML source for the Display Errors drop-down:
<tr> <td>Number purchased:</td> <td><ASP:TextBox id="txtNumPurch" runat=server width="50px" /></td>
You can then add a required field validator to ensure that some number is entered:
<td> <asp:RequiredFieldValidator id="RequiredFieldValidatorNumPurch" ControlToValidate="txtNumPurch" ErrorMessage ="You did not enter the number purchased" Width="100%" runat="server" >* </asp:RequiredFieldValidator>
And finally you can add a compare validator to ensure that the number of books purchased is greater than zero:
<asp:CompareValidator runat="server" id="CompareValidatorNumPurch" ControlToValidate="txtNumPurch" ErrorMessage ="Invalid number purchased" Type="Integer" Operator="GreaterThan" ValueToCompare=0>*</asp:CompareValidator> </td></tr>
The Compare validator takes the name of the control to validate (in this case, your text field) as well as an error message to display in the summary if the validation ...
Get Programming ASP.NET, Second 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.