如何解决Yii2唯一验证器作为即席验证器
我该如何转换:
public function rules() {
return [
[['attr1','attr2'],'unique','skipOnEmpty' => false,'skipOnError' => false,targetAttribute' => ['attr1','attr2']],
插入内联验证器,或者相当于内联验证器呢?谢谢。
解决方法
无法按照https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation中的说明将“唯一验证器”作为临时使用:
Note: Not all validators support this type of validation. An example is the unique core validator which is designed to work with a model only.
您将必须自己构建它。
其他方法可能是将查询包装到try catch中,假设您在数据库上具有唯一键。数据库将抱怨该查询,您可以捕获该错误。
编辑以进行内联验证:
这是一个非常具体的验证器,您不会重复使用,因此,请以匿名函数的形式内联编写它:
public function rules(){
[['attr1'],function(){
//we know the names of the attribute so we use them here directly instead of pass as a parameter
if(self::find()->where([
'attr1' => $this->attr1,'attr2' => $this->attr2
])->exists()){
$this->addError('attr1','Error message');
$this->addError('attr2','Error message');
}
}]
}
注意,我刚刚注册了attr1
的验证。如果还注册attr2
,则每个属性将以2个错误结束。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。