sumanta sumanta - 3 months ago 11
jQuery Question

How to validate jQuery UI Date Picker "From Date" to "To Date"

I have 2 fields "From date" and "To date". I am new in jQuery and I am learning it.


  1. When selecting from date on jQuery UI Date Picker, all previous
    dates (before current date) to be un-selectable (greyed out).

  2. When selecting to date, only dates starting from current date


    • 1 day to be selectable (cannot select same from date or date passed as to date)




I am currently using this code:

$( function() {
var dateFormat = "dd-mm-yy",
from = $( "#from" )
.datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
to.datepicker( "option", "minDate", getDate( this ) );
}),
to = $( "#to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
from.datepicker( "option", "maxDate", getDate( this ) );
});

function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}

return date;
}
});


Note: Date format should be "dd-mm-yy"

Answer

To grey out dates before current date, simply set minDate to current date in the datepicker configuration.

minDate: new Date()

You also should explicitly set the dateFormat option to be the same as the one you are using in $.datepicker.parseDate call.

If I understood your problem correctly, this fiddle should be about right (modified your code a bit)

http://jsfiddle.net/8w8v9/1846/