Search code examples
phpwebformsrequiredfieldvalidator

Using PHP Filter function to validate, but ignore empty non-required fields


I want to use the PHP Filter functions to quickly filter a form and show feedback to the user. Some of the fields in my form are required, some are not.

I am going to use filter_input_array() to filter all my fields. I will pass the data through in multiple runs. In this way, I will be able to display multiple error messages.

I have one problem: how can I ignore empty fields that are not required? I didn't see a filter for it.

Update: Clarification of the requirements for the filters and error messages:

I want to use filters to check:

  1. If all required fields are filled in
  2. If optional fields are filled in; if not, ignore for the rest of the process
  3. If fields like e-mail, phonenumber, etc. are filled in.

I want to display error messages for every type of error, with a maximum of 1 error message per field.


Solution

  • The filter_xyz_array() functions will return NULL for an element that does not exist in the input array, e.g.

    <?php
    
    $args = array(
        'foo'    => array(
            'filter'    => FILTER_VALIDATE_INT,
            'flags'     => FILTER_REQUIRE_ARRAY,
            'options'   => array('min_range' => 1, 'max_range' => 4)
        ),
        'bar'   => array(
            'filter' => FILTER_VALIDATE_INT,
            'flags'  => FILTER_REQUIRE_SCALAR
        )
    );
    
    $input = array(
        'foo'=>array(1,2,3,4)
    );
    
    $filtered = filter_var_array($input, $args);
    var_dump($filtered);
    

    prints

    array(2) {
      ["foo"]=>
      array(4) {
        [0]=>
        int(1)
        [1]=>
        int(2)
        [2]=>
        int(3)
        [3]=>
        int(4)
      }
      ["bar"]=>
      NULL
    }
    

    isset() returns false for a variable/array element that contains NULL. You can use that to ignore the elements that are set to NULL by the filter functions.
    Depending on what you're filtering and the structure of the array returned by the filter function you can even use array_filter() the "clean up" the array.