Custom filters wont work

Im setting up a form:

<?php
$item = new \CoreExt\Form\Element\Numeric(self::NAME_KILOMETER_VALUE);
$item->addFilter('naturalnumber');

in services.php, I do register this:

<?php
$filter = new \Phalcon\Filter();
$filter->add('naturalnumber', function ($value) {
  return abs((int)$value);
});

still, when I validate the form:

sanitize filter 'naturalnumber' is not supported

edited Jul '16

You are not returning filter instance from your IoC?

$di->setShared('filter', function () {

    class IPv4Filter  //TODO make pull request to Phalcon / Zephir code base with this filter
    {
        function filter($addr = null)
        {
            //Validates value as IP address, only IPv4 and not from private or reserved ranges.
return filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
        }
    }

    $filter = new \Phalcon\Filter();

    $filter->add('ipv4', new IPv4Filter());

    return $filter;
});

Usage example:

  if (!$this->filter->sanitize($ipAddressFromClient, 'ipv4')) throw new Error('Invalid client IPv4 address supplied.', 403);


12.2k

even I return this, still not work

edited Jul '16

You need to use services syntax ($di).

So, your example like this won't work UNLESS you use it in a local scope.

<?php
$filter = new \Phalcon\Filter();
$filter->add('naturalnumber', function ($value) {
  return abs((int)$value);
});

Check official documentation or use example I provided for setShared service registration.