Validation - RangeValidator

The RangeValidator does exactly what the name implies; it makes sure that the user input is within a specified range. You can use it to validate both numbers, strings and dates, which can make it useful in a bunch of cases. Since we validated numbers the last time, we will try with a date this time.

Date:<br />
<asp:TextBox runat="server" id="txtDate" />
<asp:RangeValidator runat="server" id="rngDate" controltovalidate="txtDate" type="Date" minimumvalue="01-01-2006" maximumvalue="31-12-2006" errormessage="Please enter a valid date within 2006!" />
<br /><br />

The date format might seem a bit weird to you if you're not from Europe, where we use dd-mm-yy. You can just change it if it doesn't fit the date format on the machine you're working on. Now, try running the website, and enter a date in our new TextBox. It's only valid if the date is within 2006, and a cool sideeffect is that the date is also checked for validity. Have a look at this screenshot, which shows us that the validator reacts to an impossible date as well:

And once again, if the clientside validation is not working, it will be catched in our CodeBehind, as shown with the RequiredFieldValidator. If you missed this part, then be sure to check out the first chapters!

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!