Learning While Aging

Use RangeValidator to Validate Date Entry

Suppose you would like to check if a date entered by user is not only a valid date but also meets other requirements, for instance, a date of birth cannot be later than today, the start date of a scheduled task/event needs to be later than today, etc. Of course, if possible, I would use RJS.PopCalendar to accomplish this type of task, but if third-party DLL’s are not allowed, then you can use the built-in RangeValidator to do the same thing.

Let’s add a TextBox for the date and a RangeValidator to validate the TextBox entry:

    Scheduled Start Date:
    <asp:TextBox ID="txtScheduleDate" runat="server"></asp:TextBox><br />
    <asp:RangeValidator ID="RangeValidator1" runat="server" 
        ControlToValidate="txtScheduleDate"
        ErrorMessage="The schedule date must be later than today." 
        MaximumValue="01/01/9999"
        MinimumValue="01/01/1000" 
        Type="Date">
    </asp:RangeValidator><br />

The MaximumValue and MinimumValue are required properties, so I set them with two dummy dates. Then in the Page_Load, I will overwrite them with the actual values of the required range:

'Scheduled start date cannot be one month later
Me.RangeValidator1.MaximumValue = _
        DateTime.Now.AddMonths(1).ToShortDateString()

'Scheduled start date must be at least tomorrow
Me.RangeValidator1.MinimumValue = _
        DateTime.Now.AddDays(1).ToShortDateString()

That is it. Of course you can add a RequiredFieldValidator to make sure the TextBox is not empty.

Here is a demo if you are interested in how it works.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x