Reputation: 1
I want to test invalid date, the function I wrote works fine in chrome but not in Firefox. Here are some examples not working in FF:
Above methods return "Invalid Date" in Chrome, but not in Firefox. Does anyone know the proper way to validate date in Firefox.
PS: Input string could be - mm/dd/yyyy or dd/mm/yyyy or yyyy/mm/dd
Upvotes: 0
Views: 895
Reputation: 319
You can use regex. Try this:
var rgx = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
console.log(rgx.test("99/12/2015"));
Upvotes: 1
Reputation:
I would use a internal JavaScript funtion for validating Dates, as browsers do handle those data types very differently.
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var checkDate = new Date(y, m, d);
return checkDate.getDate() == d &&
checkDate.getMonth() == m &&
checkDate.getFullYear() == y;
}
You would then use it like this:
var d = new Date(2010, 99, 1);
console.log( isValidDate(d) ); // returns false no valid date
Upvotes: 0
Reputation: 2002
It looks like Firefox takes this rule one step further than Chrome:
Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.
Source - MDN Date documentation.
The emphasis here is on with more than one argument. That's why Chrome does what Firefox does for:
new Date(2010, 99, 1);
- a valid date object.
but because:
new Date('01/99/2010');
is technically only a single argument, it doesn't fall for the above rule in Chrome, but Firefox allows it through.
With the above in mind, and the inconsistency across browsers, it looks like you might be stuck writing a validator for the day, month and year separately from trying to do it via the Date
object if you want it to work in Firefox.
Upvotes: 1