pabha pabha - 1 year ago 80
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}$/);
        if(isValid){
            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;
            }
            else{
              isValid =  false;
            }
        }
        return isValid;
    }, "Not a valid date");

$("#date").validate({
    submitHandler: function(form) {
        return false; 
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>
<form id="date" action="#" method="">
    <div>
        <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" />
    </div>
</form>

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