4

How would i go about creating custom filters for use in PHP filter_var().

An example:

Right now i have a function to validate a date:

    private function validateDate($date){
        $d = DateTime::createFromFormat('Y-m-d', $date);
        return $d && $d->format('Y-m-d') == $date;
    }

function was copied from this answer or php.net

I want to be able to call a constant like FILTER_VALIDATE_DATE and have it checked by the above code.

Any help is appreciated.

Community
  • 1
  • 1

2 Answers2

3

PHP does not have a way for you to register a custom filter, so you can't simply make a new constant to pass in. The best thing you can do is use the FILTER_CALLBACK and pass the callback in as the third argument, like so:

$valid = filter_var($date, FILTER_CALLBACK, ['options' => 'validateDate']);
Travesty3
  • 14,351
  • 6
  • 61
  • 98
0

You should use filter callback functions.

$date = "2015-06-30";

echo filter_input( $date, FILTER_CALLBACK, array('options' => 'validateDate') );
Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56