首页 > 解决方案 > 电子邮件唯一验证器 yii2 不返回消息验证

问题描述

我尝试在我的模型中对电子邮件使用唯一验证器,但它不起作用..我的意思是当用户输入已经保存在数据库中的相同电子邮件并且用户仍然可以单击提交按钮(和页面)时,不会在表单中显示通知重新加载)即使数据没有保存在数据库中。我的代码有什么问题?

这是我的模型验证:

['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\application\common\models\User', 'message' => 'This email address has been taken.'],

这是我的表格:

<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>

<?= $form->field($model,'email')->textInput()->input('email', ['placeholder' => "Email"])->label(false) ?>

...

<div class="form-group">
<?= Html::submitButton('SIGN UP NOW', ['class' => 'btn btn-sign', 'type' => 'submit']) ?>
</div>

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

这是我处理保存的模型:

if (!$this->validate()) {
     return null;
}

$user = new User();

$user->email = $this->email;
...

标签: phpyii2-advanced-appyii-validation

解决方案


您应该在模型验证中添加一个过滤器。

['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique',
          'targetClass' => '\common\models\User',
           'message' => Yii::t('frontend', 'This email address has already been taken.')
        ],

推荐阅读