RegEx - Time Validation ((h)h:mm)

后端 未结 6 1665
春和景丽
春和景丽 2021-02-13 12:46
/^\\d{1,2}[:][0-5][0-9]$/

is what I have. this limits minutes to 00-59. It does not, however, limit hours to between 0 and 12. For similarity and unifo

相关标签:
6条回答
  • 2021-02-13 13:05

    Thanks!!! I use this Javascript code now:

    function Check_arrival(time) { //Assuming you are working in 12 hour time, 0 is not a valid var patt = new RegExp("^(0?[1-9]|1[012]):[0-5][0-9]$"); var res = patt.test(time); return res; }

    res=true|false

    0 讨论(0)
  • 2021-02-13 13:09
    /^(10|11|12|[1-9]):[0-5][0-9]$/
    

    I don't think that you want 0:50 as a valid time either.

    0 讨论(0)
  • 2021-02-13 13:14

    The 0 - 9 and 10 - 12 cases need to be treated separately. (The two rules can be combined with |.)

    /^(?:0?\d|1[012]):[0-5]\d$/
    

    Here

    • (?:…) is a non-capturing group
    • x|y means match either pattern
    • 0?\d matches 0 - 9 or 00 - 09
    • 1[012] matches 10 - 12.
    0 讨论(0)
  • 2021-02-13 13:18

    This is perfect: ^0?([0-9][0-2]?):[0-5][0-9]$

    Note: 12 Hr Clock Only

    For Times like: 0:01- 12:59

    or

    00:01 - 12:59

    0 讨论(0)
  • 2021-02-13 13:22

    For folks looking for 24h format matching,

    hh:mm:ss or h:mm:ss :

    status = /^(2[0-3]|[0-1]?[\d]):[0-5][\d]:[0-5][\d]$/.test(timestr)
    

    hh:mm or h:mm :

    status = /^(2[0-3]|[0-1]?[\d]):[0-5][\d]$/.test(timestr)
    

    This site is great for testing out: https://www.regexpal.com/

    Addedum: Explanation for completeness:

    • ^ : start of string, $ : end of string. So we put the expression in a ^..$ block to ensure there's nothing outside of our pattern.
    • (2[0-3]|[0-1]?[\d]) : translates to 2[0-3] OR [0-1]?[\d]
    • 2[0-3] : 20, 21, 22, 23
    • [0-1]?[\d] : 0 or 1 or nothing (?) followed by any single digit(\d). So, this works for numbers from 0 to 19.
    • : just that character
    • [0-5][\d] : number from 00 to 59. Note: this won't tolerate single-digit in the mm place.
    0 讨论(0)
  • 2021-02-13 13:23

    Assuming you are working in 12 hour time, 0 is not a valid hour and should also be excluded (as pointed out by Jon). Here is a basic solution:

    /^(0?[1-9]|1[012]):[0-5][0-9]$/
    

    A 24-hour time regex matcher that works similarly:

    /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
    
    0 讨论(0)
提交回复
热议问题