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.
You can use scenarios for that:
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()
, likeLoginForm
andRegisterForm
. This is actually more clean solution and gives more control.EDIT
For conditional rules you should use
when
property: