Search code examples
phpfilter-input

PHP filter_validate_int for numbers with preceding zero


I want to use PHP's filter_input with FILTER_VALIDATE_INT to validate time in hours and minutes apart. the problem is that this function returns false when the time is like 03:07

$hours_range = array (
'options' => array (
    'min_range' => 0,
    'max_range' => 23
)
);

$minutes_range = array (
'options' => array (
    'min_range' => 0,
    'max_range' => 59
)
);

filter_input(INPUT_POST, 'hour', FILTER_VALIDATE_INT, $hours_range)

filter_input(INPUT_POST, 'minute', FILTER_VALIDATE_INT, $minutes_range)

Solution

  • Hmm... You could try another filter here - I would probably try FILTER_VALIDATE_REGEXP. Maybe something like:

    $mins = filter_input(INPUT_POST, 'hour', FILTER_VALIDATE_REGEXP, ['options' => [
        'regexp' => '/\d{1,2}/']
    ]);
    

    Just adding the regex \d{1,2} as an example here, clearly you might want to define something better here. Alternatively you could use FILTER_CALLBACK and define a callback inside which you can check if your value is an int and explicitly within your required numeric range.