Welcome Guest, Not a member yet? Register   Sign In
PREG_MATCH HELP
#1

[eluser]Jay Logan[/eluser]
Not really a CI related issue but maybe someone is willing to help.

I'm trying to make a callback function to validate user input of a time. Some example valid times would be:

19.26
12:34.55
1:47:23.55

Some invalid times would be:

61.92
2904.234
26:34:66



The code I use will only return TRUE if the input pattern is similar to 22:43.45. Here is what I have.

Code:
function seed_check($seed)
    {
        
        if (preg_match("/^[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}.[0-5]{1}[0-9]{1}$/", $seed))
        {
            return TRUE;
        } else {
            $this->form_validation->set_message('seed_check', 'You entered a seed time in an incorrect format. Your input input should be similar to MM:SS.LL');
            return FALSE;
        }

    }
#2

[eluser]Jay Logan[/eluser]
Never mind. Took a guess with this code and it SEEMS to work.

Code:
function seed_check($seed)
    {
        
        if (preg_match("/^([0-5]{1})?([0-9]{1}:)?[0-5]{1}[0-9]{1}.[0-5]{1}[0-9]{1}$/", $seed))
        {
            return TRUE;
        } else {
            $this->form_validation->set_message('seed_check', 'You entered a seed time in an incorrect format. Your input input should be similar to MM:SS.LL');
            return FALSE;
        }

    }
#3

[eluser]TheFuzzy0ne[/eluser]
Let us know how you get on, as I can't see how that regex would allow 1:47:23.55, although I haven't tested it.
#4

[eluser]NogDog[/eluser]
Here's what I came up with:
Code:
<?php
function isTimeString($str)
{
   $hr = '((0?|1)[0-9]|2[0-4])';
   $min = $sec = '((0?|[1-5])[0-9]|60)';
   $dec = '((0?|[1-9])[0-9])';
   $regexp = "/^(($hr:)?($min:))?$sec\.$dec\$/";
   return (bool)preg_match($regexp, $str);
}
$testData = array(
   '19.26',
   '12:34.55',
   '1:47:23.55',
   '61.92',
   '2904.234',
   '26:34:66'
);
foreach($testData as $test)
{
   echo "<p> $test: ";
   var_dump(isTimeString($test));
   echo "</p>\n";
}
Output:
Quote: 19.26: bool(true)

12:34.55: bool(true)

1:47:23.55: bool(true)

61.92: bool(false)

2904.234: bool(false)

26:34:66: bool(false)
#5

[eluser]Jay Logan[/eluser]
You are right FuzzyOne. But I don't think it is likely that a time would be an hour or more.

And thanks NogDog. I'm going to bookmark your code for the future.
#6

[eluser]TheFuzzy0ne[/eluser]
One last thought from me. Have you considered using multiple input fields in your form for the time, and validating them individually?




Theme © iAndrew 2016 - Forum software by © MyBB