Yii2验证注册身份证号不在死亡登记表中的实现求助
Got it! I see what you need here—your current exist validator is set to check if the ID exists in the deathregister table, but you want the exact opposite: verify that the input national ID does not belong to a deceased person.
Yii2's built-in exist validator has a simple but powerful negate property that flips its validation logic. Here's the adjusted code you need:
['identitynumber', 'exist', 'targetClass' => Deathregister::className(), 'targetAttribute' => ['nationalidnum' => 'idnum'], 'negate' => true, // This line reverses the validation check 'message' => 'The ID number supplied belongs to a deceased person.' ]
Key Changes Explained:
'negate' => true: This is the critical addition. By default,existchecks if a matching record exists in the target table. Settingnegatetotruereverses this—now it will throw an error if a matching record is found indeathregister.- Updated the error message slightly for better clarity (feel free to adjust this to match your system's tone).
If you're working with an older Yii2 version (pre-2.0.14, when negate was added), you could create a custom validator method as a fallback:
public function checkNotDeceased($attribute, $params) { $exists = Deathregister::find()->where(['idnum' => $this->$attribute])->exists(); if ($exists) { $this->addError($attribute, 'The ID number supplied belongs to a deceased person.'); } }
Then use it in your rules:
['identitynumber', 'checkNotDeceased'],
But the negate approach is the cleanest, built-in solution for modern Yii2 installations. Just double-check that your Deathregister model is properly imported, and the attribute mapping (nationalidnum from your form to idnum in the death table) is accurate.
内容的提问来源于stack exchange,提问作者Donaman86

