最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Max Date using JQuery Validation - Stack Overflow

programmeradmin5浏览0评论

How can I set a max date (of the current date) using Jquery Validation?

$('#form').validate({
        rules: {
            reportDate: {
                date: true
                //Max date rule of current date...
            }
        }
    });

How can I set a max date (of the current date) using Jquery Validation?

$('#form').validate({
        rules: {
            reportDate: {
                date: true
                //Max date rule of current date...
            }
        }
    });
Share Improve this question asked Jun 26, 2013 at 2:05 ojhawkinsojhawkins 3,27816 gold badges53 silver badges69 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

You can add a validation method to set max date as current date using addMethod as this

$.validator.addMethod("maxDate", function(value, element) {
    var curDate = new Date();
    var inputDate = new Date(value);
    if (inputDate < curDate)
        return true;
    return false;
}, "Invalid Date!");   // error message

and then add this method to the rules to set validation

$("#frm").validate({
    rules: {
        reportDate: {
            required: true,
            date: true,
            maxDate: true
        }
    }
});

Note: the date '12/03/2013' is interpreted as this 'mm/dd/yyyy',
so 12/03/2013 > 06/26/2013 (today's date) and hence Invalid.

Demo

You need a validation method and the date formatting is critical. Using the datepicker formatting functions helps. Here is code where you can pass the date to check and the date format as parameter. Passing "0" as date takes "today".

/**
 * Requires Datepicker and Validator
 *
 * Params: 
 * 0...dateformat. see datepicker
 * 1...date. Value "0" is "today"
 * 2...(optional). date to display. will be automatically filled if 0 and 1 are set.
 * usage:
 * myfield: { maxDate: ['m/d/yy', 0] }
 */
jQuery.validator.addMethod("maxDate", 
    function(value, element, params) {
        if (!params[0])
            throw 'params missing dateFormat';
        if (typeof(params[1]) == 'undefined' )
            throw 'params missing maxDate';

        var dateFormat = params[0];
        var maxDate = params[1];
        if (maxDate == 0) {
            maxDate = new Date();
            maxDate.setHours(0); // make it 00:00:0
            maxDate.setMinutes(0);
            maxDate.setSeconds(0);
            maxDate.setMilliseconds(0);
        }
        if (typeof(params[2]) == 'undefined' )
            params[2] = $.datepicker.formatDate(dateFormat, maxDate);

        try {
            var valueAsDate = $.datepicker.parseDate( dateFormat, value )
            return (valueAsDate < maxDate);
        } catch (x) {
            return false;
        }

    },'Must be before {2}.');


$("#myform").validate({
    rules: {
        datepicker : { 
            maxDate ['m/d/yy', 0]
        }
    }
});

HTML:

<input name="datepicker" class="datepicker" type="text"/>

I think it is more elegant solution because you can change date format as you like and use it with datepicker.

// Datepicker
$('#date_start').datepicker({
    dateFormat: 'dd.mm.yy',
    maxDate: "+0",
    onClose: function() {$(this).valid();},
}).datepicker("setDate", new Date());


// Validation method
$.validator.addMethod("maxDate", function(e) {
    var curDate = $('#date_start').datepicker("getDate");
    var maxDate = new Date();
    maxDate.setDate(maxDate.getDate());
    maxDate.setHours(0, 0, 0, 0); // clear time portion for correct results
    console.log(this.value, curDate, maxDate);
    if (curDate > maxDate) {
        $(this).datepicker("setDate", maxDate);
        return false;
    }
    return true;
});


//Date validation
$("#form").validate({
    // Rules for form validation
    rules: {
        date_start:{
            required: true,
            maxDate: true
        },
    },

    messages: {
        date_start:{
            required: 'Enter date_start',
            maxDate: 'Must be today date or less',
        },
    },
    //Error placement
    errorPlacement: function (error, element) {
       error.insertAfter(element.parent());
    }
});

//HTML
<input type="text" name="date_start" id="date_start">
发布评论

评论列表(0)

  1. 暂无评论