如何解决Yii2验证表记录条目在另一个表中不存在
我正在yii2中开发一个系统,该系统可以验证national_ID条目不属于死者。所以我有一个表registration1和deathregister表。我希望当我在registration1中输入条目时,应该验证输入的ID号在表deathregister中不存在。
目前,我有这段代码仅用于验证记录是否存在,我想要帮助的问题是对其进行自定义以检查记录是否不存在。
['identitynumber','exist','targetClass' => Deathregister::className(),'targetAttribute' => ['nationalidnum' => 'idnum'],'message'=>'The ID number Supplied Belongs to the Dead'],
解决方法
如Bizley所建议,您应该手动进行。我认为您需要的是这样的东西。您可以运行一个自定义验证器,该验证器将为错误添加或不添加错误(基于它认为有效的空错误数组)
public function rules()
{
return [
['identitynumber','notExistsValidator'],];
}
public function notExistsValidator()
{
if(!Deathregister::findOne(['nationalidnum' => $this->identitynumber])->exists())
{
$this->addError('nationalidnum','The ID number Supplied Belongs to the Dead');
}
}
,
由于使用了“ exist
”,因此“ unique
”验证器检查表列中的输入值是否唯一。
与之前的targetClass
,targetAttribute
,filter
一样,它对唯一有效。
注意:仅适用于Active Record模型属性
但是您也可以使用以下方法:
内联验证器:
return [
['identitynumber','unique','targetClass' => Deathregister::className(),'targetAttribute' => ['nationalidnum' => 'idnum'],'message'=>'The ID number Supplied Belongs to the Dead'
/*Also,if validation of one attribute depends on the value of another attribute */
// 'when' => function ($model) {
// if (condition) {
// return $this->addError('identitynumber',Yii::t('user','The ID number Supplied Belongs to the Dead'));
// }
// return false;
// }
],];
示例2:
return [
// validatorMethod()
['identitynumber','validatorMethod'],// or
['identitynumber',function ($attribute,$params) {
if(!Deathregister::findOne(['nationalidnum' => $this->$attribute])->exists()) {
$this->addError($attribute,'The ID number Supplied Belongs to the Dead.');
}
}],];
// validatorMethod()
public function ValidatorMethod($attribute,$params)
{
if(!Deathregister::findOne(['nationalidnum' => $this->$attribute])->exists()) {
$this->addError($attribute,'The ID number Supplied Belongs to the Dead');
}
}
/** Or */
// public function validatorMethod()
// {
// if(!Deathregister::findOne(['nationalidnum' => $this->identitynumber])->exists())
# code ...
// }
// }
您还可以扩展类(独立验证器)
最好参考此page和此page。
Link2
注意:如果要确保始终应用规则,可以在规则声明中将skipOnEmpty
和/或skipOnError
属性配置为false。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。