We help IT Professionals succeed at work.

I need to validate the date field using jQuery UI Date Picker

curiouswebster
on
I plan on using a text field in conjunction with the Date Picker, but neeed to add some validation for when the user types in an invalid date. When they use the calendar control, it's pre-validated. But when they type it they may enter 6/31/2011, for example.

I was told this code finds an invalid date and reports that to the user. But it doees not work.

I assume when the date in the text field does not match what's in the date picker, it's an invalid date. True?


onClose: function (dateText, inst) {
  if (dateText != $.datepicker.formatDate($.datepicker.regional[''].dateFormat, Date.parse  (dateText)))
  {
      alert("The date you specified is not a valid date.");
      this.value = '';
  }
}

This does not report an invalid date and it also prevents the calendar rom opening on mouse click, when the field is not empty.

Can someoen please telll me what I am doing wrong?

Thanks.
Comment
Watch Question

Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
replace : if (dateText != $.datepicker.formatDate($.datepicker.regional[''].dateFormat, Date.parse  (dateText)))
by :   if (dateText != $.datepicker.formatDate($.datepicker.regional[''].dateFormat, new Date (dateText)))
curiouswebsterSoftware Engineer

Author

Commented:
This change works. But onlys sometimes.

If I key in an invalid date, then press the Enter key, I get odd behavior.

Sometimes, when the year it ouside of the range allowed, a new date is created and input into the text field.

I typed 2/30/2010 and clicked enter. That's an invalid date.

What got displayed was 11/2/2010. That's crazy!

Any idea how to captre the enter keypress, and be sure there is consistent validation testing?

Thanks.
curiouswebsterSoftware Engineer

Author

Commented:
Also, do you know how to return the focus to that date field after the OK button's been clicked on the error messagebox?
curiouswebsterSoftware Engineer

Author

Commented:
Thanks. I will ask them as new questions.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>What got displayed was 11/2/2010. That's crazy!

11/2/2010 is today date
pressing ENTER put the current datepicker selected date (today by default) in the textbox

Explore More ContentExplore courses, solutions, and other research materials related to this topic.