1

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.

rob006
  • 21,383
  • 5
  • 53
  • 74
Masoud92m
  • 602
  • 1
  • 8
  • 24

1 Answers1

2

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 !== '';
            },
        ],
    ];
}
rob006
  • 21,383
  • 5
  • 53
  • 74
  • password and passwrod_repeat part of user profile settings, if user want change password, enter password and this repeat, otherwise, skip paasword and password_repeat, i want just if user insert password, check password_repeat field. – Masoud92m May 17 '18 at 11:33
  • i used your code, but when user insert password_repeat compar two field, and when user insert password and skip password_repeat, don't compar two field, i even use custom function for validation, but it also work just when password_repeat is not empty! – Masoud92m May 17 '18 at 12:37