user1527152 user1527152 - 6 months ago 17
Javascript Question

Jquery, datepicker on manual entry

I have a datepicker and I noticed that if I enter manually a date, which means entering a value of the form mm/dd/yyyy without using the calendar, the date is not updated.

I would like to allow the possibility to change manually the date. Thus, I need to validate and update the date entered.

I started by trying to use the function

change
like this:

$('myDatepickerId').change(...)


It was not working so after some research I found the
onClose:
attribute.

Which I use like this:

onClose: function(date) {
this_.tripWidget.inputChanged({
date : date,
});
}


This updates the date, but I'm not sure how to validate it.

I'm looking for a function associated with datepicker to ensure that the date entered is of the correct format. Is there anyway to verify that the date is in the datepicker calendar?

Edit:

I found a related question here:
Detecting an "invalid date" Date instance in JavaScript

Then I tried (unsuccessfully) to adapt the answer to my problem:

onClose: function(date) {
this_.tripWidget.inputChanged({
if ( Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date.getTime()){
alert("Please enter a valid date.");
}
date : date,
});
}

Answer

The following code is how I solved my problem:

var comp = date.split('/');
var m = parseInt(comp[0], 10);
var d = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date2 = new Date(y,m-1,d);
if(!(date2.getFullYear() == y && date2.getMonth() + 1 == m && date2.getDate() == d)) {
                alert('Please enter a valid date.');
}
Comments