All of my input date fields require two things in the validation world of 2.0:
- AJAX MaskedEditExtender
- Range Validator
What does the MaskedEditExtender give you? Only numbers are allowed and the
_ _ / _ _ / _ _ _ _ appear magically when the text field obtains focus. Here's what it looks like in your aspx source view:
<cc1:MaskedEditExtender ID="MaskedEditExtender3" runat="server" TargetControlID="txtBrideBDay"
The key fields to look at here are the mask and the mask type. The date mask only allows for numbers and the /. If you haven't added the AJAX toolkit to your webprojects, go here http://www.asp.net.
Now for the second piece. When you want a date to fall in a certain range, for example, scheduling an appointment, obviously the date needs to be in the future. Add a RangeValidator to your text field, select a validation type of Date, and put in your minimum and maximum values. For my application, this is what my RangeValidator looks like:
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtWeddingDate" Display="None"
ErrorMessage="Wedding Date cannot be in the past." Type="Date" MaximumValue="1/1/2050" ValidationGroup="GroupContactInfo"></asp:RangeValidator>
You can see that I don't care very much about the maximum date, setting it waaaaay in the future, and I haven't set a MinimumValue at all. This will throw a runtime error as both values are required for a RangeValidator. I've done this because future is not a definite date, it's dynamic based on the date the user is filling in the form. So I have to add it dynamically, which I've chosen to do in code-behind the first time the page loads:
RangeValidator1.MinimumValue = DateTime.Now.ToShortDateString();
You can also put the value in the aspx page (which won't require compiling to change) with MinimumValue="<% =DateTime.Now.ToShortDateString() %>".
As always with the special validators, a RequiredField validator is needed for the RangeValidator to kick in.
Onward validation soldiers!