I need to validate a date string in a specific format in Javascript.
The format is: MM/dd/yyyy hh:mm tt
I’m having a really hard time trying to find either a date library that will handle it, or a regex function that will do the same.
I’ve tried Date.js, which is close, but has the following problem:
date.parseExact('10/21/2011 06:00 AM', ['MM/dd/yyyy hh:mm tt']); //passes
date.parseExact('10/21/2011 06:00 A', ['MM/dd/yyyy hh:mm tt']); //passes
That second one should not pass.
Does anyone know of a Regex that could satisfy this need, or perhaps am I using the Date.js library wrong? Any help would be appreciated, I’ve been banging my head against the wall for the better part of 2 hours.
Do you need to validate that it is an actual date, or just that it follows that exact format? If just the format, you can use this regex:
You could use Date.js in combination with the above regex to validate that it is a valid date, and matches your exact format. Examples:
Full JS example: