Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max Date using JQuery Validation

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...
            }
        }
    });
like image 518
ojhawkins Avatar asked Jan 21 '26 18:01

ojhawkins


2 Answers

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

like image 59
Uttara Avatar answered Jan 23 '26 07:01

Uttara


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"/>
like image 37
leobard Avatar answered Jan 23 '26 06:01

leobard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!