0

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.

4

3 に答える 3

2

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:

/[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [aApP][mM]/

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:

01/01/9999 01:00 AM - matches
12/31/9999 01:59 PM - matches
99/99/9999 99:99 AM - no match (day/month out of range)
12/31/9999 99:59 PM - no match (hours out of range)
01/01/9999 99:99 A  - no match (no match on A)

Full JS example:

var re = /[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [AP][M]/; // [aApP][mM] for case insensitive AM/PM
var date = '10/21/2011 06:00 AM';
if (re.test(date) && date.parseExact(date, ['MM/dd/yyyy hh:mm tt']){
    // date is exact format and valid
}
于 2012-10-03T22:17:27.180 に答える
2

A stricter regex:

/[01]\d\/[0-3]\d\/\d{4} [01]\d:[0-5]\d [AP]M/
于 2012-10-03T22:23:09.230 に答える
0

Try this regular expression for the format dd/MM/yyyy hh:mm tt

"[0-3][0-9]\/[0-1][0-9]\/[0-9]{4} [0-1][0-9]:[0-5][0-9] [paPA][Mm]" 

the above expression works as the below formats

01/12/9999 01:00 AM - matches
12/31/9999 01:59 PM - no match
39/19/9999 01:59 PM - matches
39/19/9999 99:99 PM - no match (time out of range)
12/31/9999 99:59 PM - no match (hours out of range)
于 2016-04-02T10:37:07.357 に答える