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

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);
    }


145.0k
Accepted
answer

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