We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Troubles adding custom filter to validation

I'm trying to add a custom filter to a Validation instance, here is my filter:

class Geolocation {
    public function filter($value) {
        // filtering...
    }
}

Here is the way I'm using it:

$validation = new Validation();
$validation->add('geolocation', new PresenceOf([
    'message' => 'The geolocation is required'
]));
$validation->setFilters('geolocation', new Geolocation());
$messages = $validation->validate([
    'geolocation' => '43.139686,5.820526'
]);

When I'm running this piece of code, I get a fatal error saying: "Object of class BCosta\Filter\Geolocation could not be converted to string" on $validation->validate() line. I followed this documentation: https://docs.phalcon.io/en/latest/reference/validation.html#filtering-of-data which says:

You can add more filters to this component or use the built-in ones.

I also found this discussion: https://github.com/phalcon/cphalcon/issues/2498 where phalcon says

You can register the filter in Phalcon\Filter with a closure and then use it in Phalcon\Validation

But it's not clear to me how to perform this.

Obviously there is something I'm doing wrong but I can't seem to find what...

What is the proper way to add a custom filter to a validation instance?

Thanks in advance.

Try:

$validation->setFilters('geolocation', [new Geolocation()]);

This is not working.

$di->setShared('filter', function() {
    $filter = new Filter();
    $filter->add('geolocation', new Geolocation());
    return $filter;
});

Geolocation filter is now available everywhere.