Need to validate MM/dd/yyyy hh:mm tt in Javascript

前端 未结 3 832
悲哀的现实
悲哀的现实 2021-01-28 13:19

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 da

3条回答
  •  有刺的猬
    2021-01-28 14:06

    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
    }
    

提交回复
热议问题