Throw Exception When Filter Function Validation Fails in PHP 8.5

Throw Exception When Filter Function Validation Fails in PHP 8.5

PHP offers a range of filter functions, like filter_var and filter_input, to validate variables or superglobals against specified validation rules and parameters. By default, when validation fails, a filter function returns false. We can also configure it to return null by passing the FILTER_NULL_ON_FAILURE flag to the function.

<?php

var_dump(filter_var('example.com', FILTER_VALIDATE_URL)); // false
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)); // null

Since PHP 8.5, we can pass the FILTER_THROW_ON_FAILURE flag to filter functions to trigger an exception whenever validation fails.

<?php

// Fatal error: Uncaught Filter\FilterFailedException
filter_var('example.com', FILTER_VALIDATE_URL, FILTER_THROW_ON_FAILURE);

Callers no longer need to check validation results and throw exceptions themselves, simplifying the code.

Note that FILTER_THROW_ON_FAILURE and FILTER_NULL_ON_FAILURE flags cannot be used together. Attempting to combine them will immediately trigger a ValueError.

Leave a Comment

Cancel reply

Your email address will not be published.