#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2016
    Location
    Lakewood, WA
    Posts
    98
    Rep Power
    17

    Validating 24 hour time


    I'm trying to use preg_match to validate a 24 hour time input.

    The range validation is giving me problems.

    the number must be 0000 and 2359.

    I've got the 4 digit part down, but am have problems with the range.

    Suggestions?
  2. #2
  3. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,019
    Rep Power
    9616
    The basic form for validating the hour is validating each digit left to right:
    if it starts with 0 then it's 00-09, if it starts with 1 then it's 10-19, and if it starts with 2 then it's 20-23
    Code:
    (0[0-9]|1[0-9]|2[0-3])
    or simply
    ([01][0-9]|2[0-3])
    The minute form would go the same way, except you don't need a special form for the 50-59 range - you can just validate each digit separately.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2016
    Location
    Lakewood, WA
    Posts
    98
    Rep Power
    17
    /^(([0-1][0-9]|2[0-3])[0-5][0-9])$/ is what I arrived at, which looks the way you did it.

    Can you recommend a tutorial or other decent resource for learning?
  6. #4
  7. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,019
    Rep Power
    9616
    Not really, unfortunately. I tend to just read technical documentation.

    Lots of people will cite regular-expressions.info. PHP has the PCRE syntax, which will apply to most any place that uses the PCRE library(ies), and I think it's written in a nicer way than the perlre docs (which have a few more features than the baseline PCRE). Javascript uses a subset of PCRE so you can check out the MDN, and .NET uses something mostly compatible (IIRC) with PCRE so there's MSDN too.

IMN logo majestic logo threadwatch logo seochat tools logo