0

This is my requirement for validating a string that could be between 1 and 4 characters long (H stands for hour and M stand for minutes):

1 character = H (digit between 0-9)

2 characters = HH (first H is digit between 0-2, second is digit between 0-9, but if the first one is 2 the second one can only be 0-4)

3 characters = HMM (first H is digit between 0-9, first M is digit between 0-5, second M is digit between 0-9)

4 characters = HHMM (first H is digit between 0-2, second is digit between 0-9, but if the first one is 2 the second one can only be 0-4, first M is digit between 0-5, second M is digit between 0-9)

What makes this challenging is that I don't know the length of the string in advance and the same number could mean different things depending on how long the string is. Any ideas about a JavaScript RegularExpression to validate this?

lukegf
  • 2,147
  • 3
  • 26
  • 39
  • You can get the length of the string with `str.length` if you wanted to. Also, it's not particularly difficult to combine multiple expressions into one: http://www.regular-expressions.info/alternation.html. I would start from there and then refactor the expression to avoid repetition. – Felix Kling Oct 14 '12 at 18:33
  • Where is the string coming from, that you don't know its length? – David Thomas Oct 14 '12 at 18:34
  • Have a look at [Regular expression to validate valid time](http://stackoverflow.com/questions/884848/regular-expression-to-validate-valid-time) for a start. – Felix Kling Oct 14 '12 at 18:37
  • With Regex if you don't know the length, you can always use positive quantifiers: http://www.regular-expressions.info/possessive.html – Eric Leroy Oct 14 '12 at 18:39
  • The user enters it in a grid, they could enter anywhere between 1 and 4 characters. – lukegf Oct 14 '12 at 18:40

1 Answers1

1

You can use a regular expression like this:

^(2[0-4]|[01]?\d)([0-5]\d)?$

Breakdown:

^                   beginning of string
2[0-4]              digit 2 followed by digit 0-4
|                   or
[01]?\d             digit 0-1, optional, followed by any digit
([0-5]\d)?          digit 0-5 followed by any digit, as whole optional
$                   end of string

Note: Perhaps you mean to have hours 0-23 instead of 0-24:

^(2[0-3]|[01]?\d)([0-5]\d)?$
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • This fails for `9` and `215` which are both valid according to the question. I think it should be `^(\d|2[0-4]|[01]\d)([0-5]\d)?$` – Bill Oct 14 '12 at 18:46
  • Right, the user could enter just 9, which should be interpreted as 09 hours. I think Bill has it right, but Guffa was very close (and yes, it should be 0-23 hours). Thanks to both of you! – lukegf Oct 14 '12 at 19:15
  • @Bill: Right, thanks for spotting that. The `[01]` should simply be optional to allow single digit hours. – Guffa Oct 14 '12 at 21:39