ASP.NET Validation Part 3 Range Validator
This tutorial is the third part of the ASP.NET Validation tutorial series. This tutorial will demonstrate how to use the range validator for server side validation using ASP.NET 4.0.
What is the RangeValidator?
The range validator is an ASP.NET control that allows us to compare the value of a given control to a specified range of values. If the value of the control is outside of the specified range, an error will be thrown and the page will not be validated. The range validator utilizes server side validation. An example of where you could use this would be in a scenario where you need the user to enter in a valid quantity of items to purchase from your web site.
Using the RangeValidator
To demonstrate how to use the range validator, we will create a simple web site with a text box and a button. When the button is clicked, the value of our text box will be checked for validation by a range validator which will determine whether or not to display an error and validate the page. To do this, create a new ASP.NET Empty Web Site and:
- Right click the project in your solution explorer.
- Select add new item…
- Select a web form.
- Name it ‘Default.aspx’.
- Click add.
- Open Default.aspx up to design mode.
- Drag and drop a textbox onto the web form.
- Drag and drop a rangevalidator onto the web form.
- Set the ErrorMessage property to ‘Input is not valid.’
- Change the MaximumValue property to ’10’.
- Change the MinimumValue property to ‘1’.
- Set the Type property to ‘Integer’.
- Change the ControlToValidate property to ‘TextBox1’.
- Add a break line.
- Drag and drop a button onto the web form.
This has created a simple web page with a text box that is associated with a range validator, and a button that causes validation. The range validator takes the value of the control it is set to validate and attempts to convert that value to the specified type. Once converted, it then applies a comparison of the specified type to the value to ensure that it is between the maximum and minimum specified values. The following are the valid types of the range validator:
It is important to note that if your minimum or maximum values cannot be converted to the specified type an exception will be thrown.
Next, we will need to test a few different scenarios to demonstrate how the range validator works. To test this, enter the following data and click the button to see the result:
|Empty||No error is thrown, this is because no error will be thrown when the field is empty.|
|4||No error, the data is within our range.|
|15||Error, the data was not in our range.|
|‘asdf’||Error, the data was not converted.|
Notice that when the data field is empty an error is not thrown, even though the empty value is not within our range. This can be fixed by applying a required field validator to the control as well. Also, when data cannot be converted to the proper type for comparison, an error will always be displayed.
Download Source Files