Skip to content Skip to sidebar Skip to footer

Need To Validate Mm/dd/yyyy Hh:mm Tt In Javascript

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

Solution 1:

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/999901:00 AM -matches12/31/999901:59 PM -matches99/99/999999:99 AM -nomatch (day/monthoutofrange)
12/31/999999:59 PM -nomatch (hours outofrange)
01/01/999999:99 A  -nomatch (nomatchon 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/PMvar 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
}

Solution 2:

A stricter regex:

/[01]\d\/[0-3]\d\/\d{4} [01]\d:[0-5]\d [AP]M/

Solution 3:

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/999901:00 AM -matches12/31/999901:59 PM -nomatch39/19/999901:59 PM -matches39/19/999999:99 PM -nomatch (timeoutofrange)
12/31/999999:59 PM -nomatch (hours outofrange)

Post a Comment for "Need To Validate Mm/dd/yyyy Hh:mm Tt In Javascript"