Javascript regexp for numbers between 00-59 (in seconds)

I want to check if a field is a valid time value (just a few seconds). So I want to accept numbers from 0 to 59. I came out with this:

[0-5][0-9]?

      

which almost does the job. But it excludes the digits 7-8-9 ... It works if the custom digit is 07, but I don't want to force the user to the digit of the first 0. So I tried something like this:

([0-5][0-9]? | [0-9]) 

      

but that doesn't work and throws too many recursive calls error.

Any idea?

+3


source to share


4 answers


In the second regex, you need to remove this ?

from the first part and do it [1-5]

instead [0-5]

:

[0-9]|[1-5][0-9]

      

And if you want to be flexible enough to allow both 7

and 07

use [0-5]

:



[0-9]|[0-5][0-9]  

      

And then, simplifying the above expression, you can use:

[0-5]?[0-9]   // ? makes [0-5] part optional

      

+6


source


This should be enough: [0-5]?\d



However, if you want to apply two digits (i.e. 01

, 02

...), you should simply use[0-5]\d

+1


source


If you want to make the tens digit optional rather than the device position, put ?

there:

[0-5]?[0-9]

      

0


source


If you want 0 to be optional, ?

only move after [0-5]

.

[0-5]?[0-9]

should do it.

0


source







All Articles