Checking time with am and pm using JavaScript RegEx

I am not very familiar with regex. I have the following time: 12:00am .

I need a Javascript regex that respects this format: hh:mm[am/pm]

 var regex = /^(\d\d):(\d\d)\s?(?:AM|PM)?$/; 
+4
source share
4 answers

You are almost done, the missing part is dozens that will never be more than 1 in hours and 5 minutes. I also added an ignore case flag at the end that accepts "am", "AM", "Am", "aM":

 var regex = /^([0-1]\d):([0-5]\d)\s?(?:AM|PM)?$/i; 

Slightly more restrictive (1? Hour? 12):

 /^([1-9]|1[0-2]):([0-5]\d)\s?(AM|PM)?$/i 

Doc: http://www.javascriptkit.com/javatutors/redev.shtml .

+8
source

Below RegEx should work. Demo script

 var regex = /^([0]\d|[1][0-2]):([0-5]\d)\s?(?:AM|PM)$/i; /* The below lines are just for demo testing purpose */ var timeStr = ["13:59am","11:59AM","09:69PM", "09:24pm", "09:99pm", "15:23bm", "09:23 AM", "14:74 PM"]; for (i=0; i<timeStr.length; i++) console.log("Time String: "+timeStr[i]+ " Result: " +regex.test(timeStr[i])); 

RegEx Explanation:

([0]\d|[1][0-2]) - For the hours. Either 0 , followed by any digit (or) 1 , followed by any single digit between 0-2 (i.e. 0 or 1 or 2). This is done so that the clock value, for example 13 or 14, etc., is considered invalid (since we use time in AM / PM format, the clock value should be no more than 12).

([0-5]\d) - for minutes. Any digit between 0-5 , and then another digit between 0-9 . This is to ensure that in minutes, such as 64, 79, etc. They were considered invalid.

\s? - 0 or 1 space

(?:AM|PM)$/i - case insensitive AM or PM (that is, am | pm | Am | Pm | aM | pM | AM | PM )

Console exit:

  Time String: 13:59 am Result: false
 Time String: 11:59 AM Result: true
 Time String: 09:69 PM Result: false
 Time String: 09:24 pm Result: true
 Time String: 09:99 pm Result: false
 Time String: 15: 23bm Result: false
 Time String: 09:23 AM Result: true
 Time String: 14:74 PM Result: false  
+3
source

Below I tested it with RegExr http://www.regexr.com/3btsp

/^([0]?[1-9]|1[0-2]):([0-5]\d)\s?(AM|PM)$/i

+1
source
 ^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$ 
0
source

Source: https://habr.com/ru/post/1501435/


All Articles