Samat  Zhanbekov
Samat Zhanbekov

Reputation: 413

Custom validation filter on yii2

I need to filter data that come from hmtl form from html tags, quotes etc.

It seems that I need to write my own filter callback function according to http://www.yiiframework.com/doc-2.0/yii-validators-filtervalidator.html . I got these rules in my model:

 public function rules()
    {
        return [
            [['name', 'email', 'phone',], 'required'],
            [['course'], 'string',],
            [['name', 'email', 'phone',], 'string', 'max'=>250],
            ['email', 'email'],
            [['name', 'email', 'phone'], function($value){
                return trim(htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8'));
            }],

        ];
    }

Last rule is my own filter that i added. But it is not working. Tags, spaces, qoutes don't remove from and this filter is not even running. How to achieve what i want and what i'm doing wrong?

Thank you

Upvotes: 4

Views: 11701

Answers (1)

arogachev
arogachev

Reputation: 33538

You are adding validator wrong. If you want to use FilterValidator (which you mentioned in your question) and not inline validator, change your code like this:

[['name', 'email', 'phone'], 'filter', 'filter' => function($value) {
    return trim(htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8'));
}],

['name', 'email', 'phone'] - validated attributes.

filter - validator short name. See full list of compliances here.

The next elements are parameters that will be passed to this validator. In this case we specified filter parameter.

See full list of available parameters in official documentation to specific validator.

Upvotes: 11

Related Questions