Yii2 Compare Validator alert not disappear

10.5k views Asked by At

I type a password and then I repeat it on repeat password field but red alert didn't disappear, and when I click submit button it was success and no error validation. How to make compare alert disappear when I repeated password?

Here's my rules code in model

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', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

        ['password', 'required'],
        ['password','compare'],
        ['password', 'string', 'min' => 6],
        ['password_repeat','safe']

    ];
}

and my form

<?php $form = ActiveForm::begin(); ?>

<h3>Your Account</h3>
<?= $form->field($modelUser, 'username')->textInput(['maxlength' => 45, 'class' => 'input-xlarge form-control']) ?>

<?= $form->field($modelUser, 'password')->passwordInput(['class' => 'form-control input-xlarge']) ?>

<?= $form->field($modelUser, 'password_repeat')->passwordInput(['class' => 'form-control input-xlarge']) ?>
<button class="btn btn-primary" type="submit">Continue</button>

<?php ActiveForm::end(); ?>

and here's my screenshot yii2 compare validation

3

There are 3 answers

0
Victor On BEST ANSWER

In my case I just changed password validation from this:

['password','compare'],

to this:

['password_repeat', 'compare', 'compareAttribute' => 'password'],
0
Claudio Eddy On

If I understood you correctly: you type the first password and, as you change focus to the other field (password_repeat), the form already shows an error message even though you haven't even typed the second field. If it's that, you could disable client validation, so that the data would be validated only after you submit the form. To do so, you could add the following to your ActiveForm initialization (it's an option):

<?php $form = ActiveForm::begin(['enableClientValidation' => false']);?>
0
Liz On

I just only needed this line:

[['password_repeat'], 'compare', 'compareAttribute' => 'password', 'message' => 'Your error message']