Reputation: 20419
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.
Upvotes: 1
Views: 1463
Reputation: 585
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);
};
Upvotes: 0
Reputation: 1056
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.
Upvotes: 2