We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Filtering data before validation and database update

My goal is to strip spaces from several fields in my model before validation and database update. I have tried to use setFilters in the validation method in the model without luck. What is the correct way to accomplish this?

Example: " 86 786 99 " will become "8678699"

Added to services.php:

$di->setShared('filter', function() {
    $filter = new \Phalcon\Filter();
    $filter->add('stripspaces', new \KitCloud\Module\Core\Filter\StripSpaces());
    return $filter;
});

StripSpaces.php:

namespace KitCloud\Module\Core\Filter;

class StripSpaces
{
    public function filter($value)
    {
        return preg_replace('/\s+/', '', $value);
    }
}

Entity validation function:

    public function validation()
    {
        $validator = new Validation();

        $validator->add(
            'phone',
            new Regex(array(
                'pattern' => '/^([0-9]{8})?$/',
                'message' => sprintf(_('%s is not valid'), _('Phone number')).' ('.sprintf(_('%d digits'), '8').')'
            ))
        );

        $validator->setFilters('phone', 'stripspaces');

        return $this->validate($validator);
    }


144.9k
Accepted
answer

Filters in model validation will work form 3.0.2 when realsed. You can already compile it using zephir.