- Overview of the Validation Controls
- Using the RequiredFieldValidator Control
- Using the RangeValidator Control
- Using the CompareValidator Control
- Using the RegularExpressionValidator Control
- Using the CustomValidator Control
- Using the ValidationSummary Control
- Creating Custom Validation Controls
- Summary
Using the RangeValidator Control
The RangeValidator control enables you to check whether the value of a form field falls between a certain minimum and maximum value. You must set five properties when using this control:
- ControlToValidate— The ID of the form field being validated.
- Text— The error message displayed when validation fails.
- MinimumValue— The minimum value of the validation range.
- MaximumValue— The maximum value of the validation range.
- Type— The type of comparison to perform. Possible values are String, Integer, Double, Date, and Currency.
For example, the page in Listing 3.9 includes a RangeValidator that validates an age form field. If you do not enter an age between 5 and 100, then a validation error is displayed (see Figure 3.7).
Figure 3.7 Validating a form field against a range of values.
Example 3.9. ShowRangeValidator.aspx
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show RangeValidator</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblAge" Text="Age:" AssociatedControlID="txtAge" Runat="server" /> <asp:TextBox id="txtAge" Runat="server" /> <asp:RangeValidator id="reqAge" ControlToValidate="txtAge" Text="(Invalid Age)" MinimumValue="5" MaximumValue="100" Type="Integer" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> </div> </form> </body> </html>
If you submit the form in Listing 3.9 with an age less than 5 or greater than 100, then the validation error message is displayed. The validation message is also displayed if you enter a value that is not a number. If the value entered into the form field cannot be converted into the data type represented by the RangeValidator control's Type property, then the error message is displayed.
If you don't enter any value into the age field and submit the form, no error message is displayed. If you want to require a user to enter a value, you must associate a RequiredFieldValidator with the form field.
Don't forget to set the Type property when using the RangeValidator control. By default, the Type property has the value String, and the RangeValidator performs a string comparison to determine whether a values falls between the minimum and maximum value.