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

Last Reply 11 months ago By dharmendr

Posted 11 months ago

hello,

i am using this snippet it works fine https://www.aspsnippets.com/Demos/823/

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

Posted 11 months ago

Hi nauna,

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

HTML

<div>
    <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>
</div>
<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;
        }
    }
</script>

Screenshot