javascript regexp for numbers between 00-59 (seconds)

前端 未结 4 907
栀梦
栀梦 2021-01-19 15:03

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

[0-5][0-9]?
相关标签:
4条回答
  • 2021-01-19 15:44

    If you want the 0 to be optional, move the ? to just after the [0-5] instead.

    [0-5]?[0-9] should do it.

    0 讨论(0)
  • 2021-01-19 15:45

    If you want to make the tens digit optional, not the unit position, place the ? there:

    [0-5]?[0-9]
    
    0 讨论(0)
  • 2021-01-19 15:49

    In your 2nd regex, you need to remove that ? from the first part, and make it [1-5] instead of [0-5]:

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

    And if you want to be flexible enough to allow both 7 and 07, then use [0-5]:

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

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

    [0-5]?[0-9]   // ? makes [0-5] part optional
    
    0 讨论(0)
  • 2021-01-19 15:50

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

    However if you want to enforce two digits (ie. 01, 02...) you should just use [0-5]\d

    0 讨论(0)
提交回复
热议问题