Yii2比较验证器警报不会消失

时间:2014-10-14 05:30:27

标签: validation passwords compare yii2 comparevalidator

我键入密码,然后在重复密码字段重复,但红色警报没有消失,当我点击提交按钮时,它成功,没有错误验证。 当我重复密码时如何使比较警报消失?

这是我在模型中的规则代码

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']

    ];
}

和我的表格

<?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(); ?>

这是我的截图 yii2 compare validation

3 个答案:

答案 0 :(得分:16)

就我而言,我刚刚更改了密码验证:

['password','compare'],

到此:

['password_repeat', 'compare', 'compareAttribute' => 'password'],

答案 1 :(得分:2)

如果我理解正确:您键入第一个密码,并且当您将焦点更改为其他字段(password_repeat)时,即使您甚至没有输入第二个字段,表单也会显示错误消息。如果是这样,您可以禁用客户端验证,这样只有在您提交表单后才能验证数据。为此,您可以将以下内容添加到 ActiveForm 初始化(这是一个选项):

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

答案 2 :(得分:0)

我只需要这一行:

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