Reputation: 2972
I am using compareValidator in yii2 form.
Here is the code
[['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],
It should work fine because its the code in the documentation as well
But what happens is it only validates the password once.
For example if I input password and Confirm Password once it will validate fine but if I go back to the password field and change the password than it doesn't compare confirm password input with new password input
Anybody else having the same problem??? or I did something wrong here as well
Here is the model
code
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
[['passwordConfirm'], 'compare', 'compareAttribute' => 'password'],
];
}
public function attributeLabels()
{
return [
'passwordConfirm' => 'Confirm Password',
'username' => 'Username',
'email' => 'Email',
];
}
And here is the view
code
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?= $form->field($model, 'username')->textInput( ['data-toggle' => 'tooltip',
'data-placement' =>
'right',
'title' => 'Username should contain at least 6 characters'
]) ?>
<?= $form->field($model, 'password')->passwordInput(['data-toggle' => 'tooltip',
'data-placement' =>
'right',
'title' => 'Password should contain at least 6 characters',
]) ?>
<?= $form->field($model, 'passwordConfirm')->passwordInput() ?>
<?= $form->field($model, 'email') ?>
<?php ActiveForm::end(); ?>
Thank you
Upvotes: 0
Views: 583
Reputation: 2300
This is the expected behavior. The validator is attached to the passwordConfirm
attribute and therefore is triggered when that attribute is changed. Specific action depends on how validateOnChange
, validateOnBlur
, and validateOnType
properties of ActiveField
are set.
However, the whole form should get revalidated before it is submitted, so you will see an error if you went back and changed the password
field.
If you absolutely need to enable validation in the scenario you describe, you can either add another compare
validator to password
attribute in backend, or add a call to validate passwordCompare
attribute when your password
field changes in frontend.
I suggest you stick to the original implementation though, because the form will get validated eventually, if not on frontend, then on backend.
Upvotes: 1