Using the RangeValidator Control


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.


Listing 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  runat="server">     <title>Show RangeValidator</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="Age:"         AssociatedControl         Runat="server" />     <asp:TextBox                  Runat="server" />     <asp:RangeValidator                  ControlToValidate="txtAge"         Text="(Invalid Age)"         MinimumValue="5"         MaximumValue="100"         Type="Integer"         Runat="server" />     <br /><br />     <asp:Button                  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.




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net