Possible Duplicate:
Detecting an “invalid date” Date instance in JavaScript
I was using the following to detect a valid date:
var text = $('#Date').val(); var date = Date.parse(text); if (isNaN(date)) { // Invalid date }
But found that Date.parse thinks the following are valid dates (mm/dd/yyyy)
Any other way to detect invalid dates when the number of days surpasses the total number of days in the month?
UPDATE: An even larger problem is that the jQuery validation plugin doesn't detect this as an invalid date either!
SOLUTION:
Based on @Guffa's comments I have created the following function to validate dates:
function validDate(text) { var date = Date.parse(text); if (isNaN(date)) { return false; } var comp = text.split('/'); if (comp.length !== 3) { return false; } var m = parseInt(comp[0], 10); var d = parseInt(comp[1], 10); var y = parseInt(comp[2], 10); var date = new Date(y, m - 1, d); return (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d); }
Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.
Using the Date. One way to check if a string is date string with JavaScript is to use the Date. parse method. Date. parse returns a timestamp in milliseconds if the string is a valid date.
mm/dd/yyyy or mm-dd-yyyy format. In the following examples, a JavaScript function is used to check a valid date format against a regular expression. Later we take each part of the string supplied by user (i.e. dd, mm and yyyy) and check whether dd is a valid date, mm is a valid month or yyyy is a valid year.
To check if a date is valid you can parse the components of the date, create a Date
object from it, and check if the components in the data is the same as the parsed components. If you create a Date
object from compnents that are out of range, the values will flow over to the next/previous period to create a valid date.
For example, new Date(2011,0,42)
will create an object that contains the date 2/11/2011 instead of 1/42/2011.
By parsing the components instead of the full date you will also get around the problem with different date formats. My browser will for example expect a date format like y-m-d
rather than d/m/y
.
Example:
var text = '2/30/2011'; var comp = text.split('/'); var m = parseInt(comp[0], 10); var d = parseInt(comp[1], 10); var y = parseInt(comp[2], 10); var date = new Date(y,m-1,d); if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) { alert('Valid date'); } else { alert('Invalid date'); }
Demo: http://jsfiddle.net/Guffa/UeQAK/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With