How to validate date in chrome browser as well as in firefox browser How to validate date in chrome browser as well as in firefox browser google-chrome google-chrome

How to validate date in chrome browser as well as in firefox browser


The Javascript Date API can have somewhat mixed results between browsers, as you've discovered.

The best option I can suggest is to use one of the third-party libraries that are available for this. There are two I can recommend -- either Moment.js or Date.js.

Both of these libs have much better validation and parsing, and are more consistent cross-browser than the built-in Date class.


The correct answer is to use a Javascript library as @Spudley suggested like moment.js.

However, if you don't want to include that awesome library (or another like it), you could try running your date through a regex like this:

var date = "9/",    pattern = /(?:(?:\d{2}[-\/]){2}\d{4})|(?:\d{4}(?:[-\/]\d{2}){2})/,    isValid = false;isValid = pattern.test( date );

This will match yyyy/mm/dd, dd/mm/yyyy, mm/dd/yyyy and yyyy/dd/mm (plus a number of variations [and issues]).

However, this is extremely naive, doesn't match the vast majority of date formats, allows mixed separators, and a wide array of other issues.

Again, I strongly recommend you implement a library like moment.js, but this regex might be a start.