yii2 上的自定义验证过滤器
Custom validation filter on yii2
我需要从 html 标签、引号等中过滤来自 hmtl 表单的数据
看来我需要根据http://www.yiiframework.com/doc-2.0/yii-validators-filtervalidator.html写一个自己的过滤器回调函数。我的模型中有这些规则:
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'));
}],
];
}
最后一条规则是我自己添加的过滤器。但它不起作用。标签、空格、引号不会从中删除,这个过滤器甚至不是 运行。如何实现我想要的和我做错了什么?
谢谢
您添加的验证器有误。如果您想使用 FilterValidator
(您在问题中提到)而不是内联验证器,请像这样更改您的代码:
[['name', 'email', 'phone'], 'filter', 'filter' => function($value) {
return trim(htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8'));
}],
['name', 'email', 'phone']
- 验证属性。
filter
- 验证者简称。查看完整的合规列表 here。
接下来的元素是将传递给此验证器的参数。在这种情况下,我们指定了 filter 参数。
在特定验证器的官方文档中查看可用参数的完整列表。
我需要从 html 标签、引号等中过滤来自 hmtl 表单的数据
看来我需要根据http://www.yiiframework.com/doc-2.0/yii-validators-filtervalidator.html写一个自己的过滤器回调函数。我的模型中有这些规则:
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'));
}],
];
}
最后一条规则是我自己添加的过滤器。但它不起作用。标签、空格、引号不会从中删除,这个过滤器甚至不是 运行。如何实现我想要的和我做错了什么?
谢谢
您添加的验证器有误。如果您想使用 FilterValidator
(您在问题中提到)而不是内联验证器,请像这样更改您的代码:
[['name', 'email', 'phone'], 'filter', 'filter' => function($value) {
return trim(htmlentities(strip_tags($value), ENT_QUOTES, 'UTF-8'));
}],
['name', 'email', 'phone']
- 验证属性。
filter
- 验证者简称。查看完整的合规列表 here。
接下来的元素是将传递给此验证器的参数。在这种情况下,我们指定了 filter 参数。
在特定验证器的官方文档中查看可用参数的完整列表。