Click here to download the sample source code for this lesson.
This lesson is a continuation of the discussion regarding ASP.NET validation controls. Validation controls do not require any coding, thus saving time performing redudant tasks.
In this exercise we will cover how to ensure that the user typed information within an allowed range of values. ASP.NET offers the RangeValidator control to ensure that fields follow range rules. The RangeValidator is very easy to use; just drag it from the Toolbox window onto your web form. It is located in the Validation group in the Toolbox window, so you may have to scroll down the Toolbox to find it. You should drag the control to the location where you want the error message to show up, in case the validation fails; which in this case is if something entered in a field doesn’t match the range rule.
Once you have dragged the validator onto the web form, you need to set some of the properties. The ErrorMessage property sets what error text will be displayed in case the validation fails. The error text will be shown in red. The ControlToValidate property sets which server control to examine at runtime to see if it follows the rule. The MaximumValue property sets the largest possible value in your validation rule that is acceptable. The MinimumValue property sets the smallest possible value in your validation rule that is acceptable. Finally, the Type property lets the validator know what type of data will be validated: String, Integer, Date, etc.
Click here to watch an example video. In the example I dragged a RangeValidator next to the Age TextBox control. Notice that I set the minimum value to 18 for the age field. When I run the program, if I don’t type an age that is at least 18, the validator will display the error message.