filter_input_array -> FILTER_SANITIZE_NUMBER_FLOAT -> exept , and . in all INPUT_POST fields

1k views Asked by At

The form have 6 fields, only numbers are allowed except , and .

Now I try to use filter_input_array to check. When I use

filter_input_array(INPUT_POST, FILTER_SANITIZE_NUMBER_FLOAT);

the script change 0,5 to 05.

When I try it this way:

$filter = array('filter' => FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION);
$perf['post'] = filter_input_array(INPUT_POST, $filter);

perf['post'] looks like this:

Array ([filter] => [flags] => )

So I have to make an entry for all form fields in my $filter array? Also when i just have one rule for all fields?

1

There are 1 answers

0
Isius On

You can't currently add the flags you need (FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_FRACTION) to any of the filter array functions without specifying each field individually; although that would be nice.

Alternative options:

Specify each field

$filter = array(
    'field_one' => array(
        'filter' => FILTER_SANITIZE_NUMBER_FLOAT,
        'flags' => FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_FRACTION
    ),
    'field_two' => array(
        'filter' => FILTER_SANITIZE_NUMBER_FLOAT,
        'flags' => FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_FRACTION
    ),
    ...
);

Reuse definition array

$my_number_def = array(
        'filter' => FILTER_SANITIZE_NUMBER_FLOAT,
        'flags' => FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_FRACTION
    );

$filter = array(
        'field_one' => $my_number_def,
        'field_two' => $my_number_def,
        ...
    );

Individually

$args = FILTER_FLAG_ALLOW_THOUSAND | FILTER_FLAG_ALLOW_FRACTION;

$perf['post']['one'] = filter_input(INPUT_POST, 'postOne', FILTER_SANITIZE_NUMBER_FLOAT, $args);
$perf['post']['two'] = filter_input(INPUT_POST, 'postTwo', FILTER_SANITIZE_NUMBER_FLOAT, $args);

Manually

regex:

$perf['post'] = preg_grep('/^[0-9,.]$/', $_POST); // unverified regex!