You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yii2验证注册身份证号不在死亡登记表中的实现求助

Solution for Yii2 ID Number Deceased Check

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, exist checks if a matching record exists in the target table. Setting negate to true reverses this—now it will throw an error if a matching record is found in deathregister.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 21:53:11