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" 
        ErrorMessage="The schedule date must be later than today." 
    </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 = _

'Scheduled start date must be at least tomorrow
Me.RangeValidator1.MinimumValue = _

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.

Leave a Reply

Notify of
Close Bitnami banner