pabha pabha - 1 year ago 91
jQuery Question

how to validate date field in jquery addmethod

I need to validate the entered date in the text box using jquery in addmethod.The date not be more than the date which is 1 yr from current date and also to be in format dd/mm/YYYY. Pls any one of u help me to resolve.

jQuery.validator.addMethod("greaterThanToday", function(value, element) {
var now=new Date();
if ( !/Invalid|NaN/.test(new Date(value)) ) {
return new Date(value) > now;
return isNaN(value) || (parseFloat(value) > now); }, "* The date should not be greater than today.");

Answer Source

Try this code

jQuery.validator.addMethod("greaterThanToday",function(value) {
        var isValid = value.match(/^\d{2}\/\d{2}\/\d{4}$/);
            var datetime = value;
            var date = new Date();
            var parts = datetime.split('/');
            var day = parseInt(parts[0]);
            var month = parseInt(parts[1])-1;
            var year = parseInt(parts[2]);
            var maxyear = date.getFullYear()+1;
            var maxDay = date.getDate();
            var maxMonth = date.getMonth();
            var enteredDate = new Date(year, month, day);
            var maxDate = new Date(maxyear, maxMonth, maxDay);
            if (enteredDate <= maxDate) {
              isValid = true;
              isValid =  false;
        return isValid;
    }, "Not a valid date");

    submitHandler: function(form) {
        return false; 
<script src=""></script>
<script src=""></script>
<form id="date" action="#" method="">
        <label for="datetime">dd/mm/yyyy<input type="text" name="datetime" id="checkDate" value="23/05/2017" class="required greaterThanToday"/></label>
        <input type="submit" name="submit" id="submit" value="Check" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download