Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation filter on yii2

Tags:

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

like image 750
Samat Zhanbekov Avatar asked Dec 24 '22 23:12

Samat Zhanbekov


1 Answers

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.

like image 74
arogachev Avatar answered Jan 24 '23 11:01

arogachev