1

I have three fields for date input - day, month, year. Once it is input, I should verify it. The following code is used:

$('#test').click(function(event) {
    var daySelector = "#dd",
        monthSelector = "#mm",
        yearSelector = "#yyyy";
    var day = $(daySelector).val() == "" ? 1 : parseInt($(daySelector).val(), 10);
    var month = $(monthSelector).val() == "" ? 1 : parseInt($(monthSelector).val(), 10);
    var year = parseInt($(yearSelector).val(), 10);
    var date = new Date(year, month, day);
    var result = !isNaN(date.getTime());    
});

But it accepts (i.e. returns true) wrong values like 33/55/2000. Where is my mistake? Demo

I've tried another approach - it doesn't work well also.

LA_
  • 19,823
  • 58
  • 172
  • 308
  • 1
    You can use || instead of the ternary operator for default values when null or empty.. x = x || 1.. not your answer, but easier to read – Patrick Lee Scott Apr 09 '12 at 20:19
  • http://stackoverflow.com/questions/3876448/javascript-month-and-day-and-year-check – zod Apr 09 '12 at 20:23
  • Any chance you could use a calendar or some other single field lookup? User experience for 3 separate date fields leaves something to be desired. – Jordan Apr 09 '12 at 20:24
  • yes, and you won't need to worry about invalid input if you use something like jquery ui datepicker for example – Patrick Lee Scott Apr 09 '12 at 20:26

2 Answers2

2

Date object automaticly converts overflows.

So if you create 32.01.2000 and there are only 31 days in the january then it will create object with 01.02.2000 Date

You have to change your validation logic from "Is Nan" to something more sophisticated;)

One thing to note :)

date.getMonth() returns 0-11 -> 0 equals january :P That was the source of my initial mistake in the answer. And it seems like you have to decrement value sent to the Date constructor.

Michal Franc
  • 1,036
  • 10
  • 16
0

Consider existing solutions:

=========

UPD Just pulled out function from one of these frameworks:

validateDay = function (day, year, month) {
    var date = new Date(year, month, day);
    return (date.getFullYear() === year &&
        date.getMonth() === month &&
        date.getDate() === day);
};​
Vlad Minaev
  • 585
  • 4
  • 10
  • Re your update - see the end of my question, I've mentioned there another approach - this is equal to what you've given. And it doesn't work, date 30-feb-2000 is treated as valid. – LA_ Apr 10 '12 at 06:30
  • @LA_ maybe you've forgotten that month index starts whith 0. So January=0, February=1 (**not 2**) check this out again **it works** fine – Vlad Minaev Apr 10 '12 at 10:09
  • Thanks. For month index issue, I use the following: function ValidateDate(day, month, year) { var date = new Date(year, month-1, day); return (date.getFullYear() === year && date.getMonth() === month-1 && date.getDate() === day); }; – slmglr May 03 '23 at 09:42