Time Validator

Discussion in 'PHP' started by rafiqasad, Apr 9, 2009.

  1. #1
    I need a regular expression that validate time hh:mm:ss. Please guide me
     
    rafiqasad, Apr 9, 2009 IP
  2. Weirfire

    Weirfire Language Translation Company

    Messages:
    6,979
    Likes Received:
    365
    Best Answers:
    0
    Trophy Points:
    280
    #2
    Can you share some code so we know what sort of thing will need validating?
     
    Weirfire, Apr 9, 2009 IP
  3. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can't easily validate it with a regular expression alone. Maybe it's possible, but not worth the effort I'd say.

    Instead, try something like this (untested):
    if (preg_match('/^(\d{1,2}):(\d{1,2}):(\d{1,2})$/',
       trim($_REQUEST['time']), $matches)
       && $matches[1] < 24
       && $matches[2] < 60
       && $matches[3] < 60)
    {
       $valid_time = sprintf('%02d:%02d:%02d',
          $matches[1], $matches[2], $matches[3]);
       echo "<p>Valid time submitted: {$valid_time}</p>";
    }
    else
       echo "<p>Time was invalid.</p>";
    Code (markup):
     
    SmallPotatoes, Apr 9, 2009 IP