Yii2 form validation - compare password repeat only when password field is filled

╄→尐↘猪︶ㄣ 提交于 2020-01-14 03:10:26

问题


My form validation uses the following rules:

[['password', 'password_repeat'], 'required'],
['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => "Passwords don't match"],

How to write rules for password_repeat to compare it with password only if user fill password field. If user skip password, validation for password_repeat should be also skipped.


回答1:


You can use scenarios for that:

public function rules() {
    return [
        [['username', 'password'], 'required', 'on' => self::SCENARIO_LOGIN],
        [['username', 'password', 'password_repeat'], 'required', 'on' => self::SCENARIO_REGISTER],
        [
            'password_repeat', 'compare', 'compareAttribute' => 'password',
            'message' => "Passwords don't match", 'on' => self::SCENARIO_REGISTER,
        ],
    ];
}

This allows you to set different rules for different forms (different fields required on login and registration).

You may also consider creating different models for different forms with own rules(), like LoginForm and RegisterForm. This is actually more clean solution and gives more control.


EDIT

For conditional rules you should use when property:

public function rules() {
    return [
        [['password', 'password_repeat'], 'string'],
        [
            'password_repeat', 'compare', 'compareAttribute' => 'password',
            'message' => "Passwords don't match", 'skipOnEmpty' => false,
            'when' => function ($model) {
                return $model->password !== null && $model->password !== '';
            },
        ],
    ];
}


来源:https://stackoverflow.com/questions/50389866/yii2-form-validation-compare-password-repeat-only-when-password-field-is-fille

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!