Skip to content
Rupesh Bhochhibhoya edited this page Apr 13, 2016 · 1 revision

Recently, I have to write validation logic in javascript to check if the given string matches a specified criteria. The best way to do was to represent such criteria in regular expression. For instance, let say we want to validate the input string value. A value is a time(hr:min) or time frame(hr-hr). Following are valid inputs: 8, 8am, 8pm, 8:30, 8:30am, 8-9, 8am-9am, 8:30-9, 11:30am-1pm, 11-12pm. So, the specified criteria are:

  1. Single digit or two digits from 1 to 12.
  2. Digit suffix either with "am" or "pm"
  3. Digit suffix with ":[00 to 59]"
  4. Two digits following rules 1/2/3 separated by hypen.

Here is the regex that matches given criteria: /^((1[0-2]|0?[0-9])(:[0-5][0-9])?(am|pm)?)(-((1[0-2]|0?[0-9])(:[0-5][0-9])?(am|pm)?))?$/

ref