Past 6 months Validation from Current Date in JavaScript

Last Reply 7 months ago By dharmendr

Posted 7 months ago

hello,

i am using this script to check if date is less than 6 months or not, it works fine.

but problem is 

1. if date is less than 6 months so it gives error

2. but then user fix the data greater than 6 months still it shows the error in label 

when user correct the date it should remove error message please advice

<script type="text/javascript">
    function ValidateDOB(sender, args) {
        var dateString = document.getElementById(sender.controltovalidate).value;
        var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
        if (regex.test(dateString)) {
            var parts = dateString.split("/");
            var dt = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
            var dtCurrent = new Date();
            if (dt.getYear() == dtCurrent.getYear()) {
                if (dt.getMonth() > dtCurrent.getMonth() - 6) {
                    //document.getElementById(sender.controltovalidate).innerHTML = "Candidate has not worked for 6 months";
                    document.getElementById('<%= Label1.ClientID %>').innerHTML = "Candidate has not worked for 6 months";
                }
            }
            args.IsValid = true;
           
        } else {
            sender.innerHTML = "Enter date in dd/MM/yyyy format ONLY."
            args.IsValid = false;
        }
    }
</script>

 

Posted 7 months ago

Hi nauna,

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

HTML

<script type="text/javascript">
    function ValidateDOB(sender, args) {
        var dateString = document.getElementById(sender.controltovalidate).value;
        var regex = /(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$/;
        if (regex.test(dateString)) {
            var parts = dateString.split("/");
            var dt = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
            var dtCurrent = new Date();
            dtCurrent.setMonth(dtCurrent.getMonth() - 6);
            if (dt.getFullYear() <= dtCurrent.getFullYear()) {
                if (dt > dtCurrent) {
                    args.IsValid = true;
                } else {
                    args.IsValid = false;
                } 
            }
        } else {
            sender.innerHTML = "Enter date in dd/MM/yyyy format ONLY."
            args.IsValid = false;
        }
    }
</script>
<asp:TextBox ID="txtDate" runat="server" Text="02/07/2018" />
<asp:CustomValidator ID="cvDate" runat="server" ClientValidationFunction="ValidateDOB"
    ControlToValidate="txtDate" ErrorMessage="Candidate has not worked for 6 months."
    ValidationGroup="gp1" Display="Dynamic" ForeColor="Red" />
<br />
<br />
<asp:Button ID="btnValidate" Text="Validate" runat="server" ValidationGroup="gp1" />

Screenshot