Best way to check date string format via jQuery

I found many links to check the string if it is a date.

Like here and here .

But in any case, I can’t figure out how to check if we have this thing:

6/6/2012 , where the first 6 is a month and the second 6 is days

and also if the user enters it like this:

06/06/2012

Any hint on how to do this properly?

Thanks!!

+4
source share
2 answers

Here it should work with any date format with a 4-digit year and any separator. I extracted it from my Ideal Forms plugin, which checks dates and more.

var isValidDate = function (value, userFormat) { var userFormat = userFormat || 'mm/dd/yyyy', // default format delimiter = /[^mdy]/.exec(userFormat)[0], theFormat = userFormat.split(delimiter), theDate = value.split(delimiter), isDate = function (date, format) { var m, d, y for (var i = 0, len = format.length; i < len; i++) { if (/m/.test(format[i])) m = date[i] if (/d/.test(format[i])) d = date[i] if (/y/.test(format[i])) y = date[i] } return ( m > 0 && m < 13 && y && y.length === 4 && d > 0 && d <= (new Date(y, m, 0)).getDate() ) } return isDate(theDate, theFormat) } 
+19
source

Use regex.

 var dateRegEx = /^(0[1-9]|1[012]|[1-9])[- /.](0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](19|20)\d\d$/ console.log("06/06/2012".match(dateRegEx) !== null) // true console.log("6/6/2012".match(dateRegEx) !== null) // true console.log("6/30/2012".match(dateRegEx) !== null) // true console.log("30/06/2012".match(dateRegEx) !== null) // false 

Learn about RegEx.

Edit - Disclaimer

As @elclanrs noted, this only confirms the format string, not the actual date, which means dates like the 31st will pass. However, since the OP only asks for β€œto check the format of the date string,” I will keep this answer here, because for some, this may be all you need.

As a side note, the jQuery validation plugin used by the OP also only validates the format.

Finally, for those who are wondering if you need to check the date, and not just the format, this regular expression will have a ~ 2% rejection rate in the domain (1-12) / (1-31) / (1900-2099 ) Please do not use this in the Critical Code for JPL.

+5
source

All Articles