ojhawkins
ojhawkins

Reputation: 3288

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...
            }
        }
    });

Upvotes: 2

Views: 19502

Answers (3)

Kirill Ryzhkov
Kirill Ryzhkov

Reputation: 522

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">

Upvotes: 1

leobard
leobard

Reputation: 41

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"/>

Upvotes: 1

Uttara
Uttara

Reputation: 2532

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

Upvotes: 15

Related Questions