Date and Time validation using RegularExpression and CustomValidator in ASP.Net

on Oct 01, 2018 03:12 AM


i am using this snippet it works fine

i am using Using RegularExpressionValidator

i want to validdate date and time.

user should add valid date and valid time should be equal to or greater than current date and time.

i am not using calender control i just have textbox

i want user to type in date and time in proper format like dd/MM/yyyy 2:00

please advice

Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Oct 01, 2018 06:13 AM

Hi nauna,

Check this example. Now please take its reference and correct your code.


    <asp:TextBox ID="txtDate1" runat="server" />
    <asp:Button ID="Button1" Text="Validate" runat="server" ValidationGroup="Group1" />
    <br />
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtDate1"
        ValidationExpression="(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d) [0-2][0-9]:[0-5][0-9])$"
        ErrorMessage="Invalid format. Valid format is dd/MM/yyyy HH:mm" ForeColor="Red"
        Display="Dynamic" ValidationGroup="Group1" />
    <br />
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="DateTime should be equal or greater than current DateTime"
        ForeColor="Red" ControlToValidate="txtDate1" ClientValidationFunction="DateTimeValidation"
        Display="Dynamic" ValidationGroup="Group1"></asp:CustomValidator>
<script type="text/javascript">
    function DateTimeValidation(sender, args) {
        var enteredValue = document.getElementById("<%=txtDate1.ClientID %>").value;
        var date = enteredValue.split('/')[0];
        var month = enteredValue.split('/')[1];
        var year = enteredValue.split('/')[2].split(' ')[0];
        var enteredDateTime = new Date(month + "/" + date + "/" + year + " " + enteredValue.split(' ')[1]);
        var currentDateTime = new Date();
        if (enteredDateTime >= currentDateTime) {
            args.IsValid = true;
        else {
            args.IsValid = false;