简体   繁体   English

yii2 中未出现唯一验证器的消息

[英]Message for unique validator is not coming in yii2

I have following rule for email to be unique in modal我有以下规则,电子邮件在模态中是唯一的

   [['email'], 'unique'],

I am not using ajax to submit form.没有使用ajax提交表单。 Problem is that I am getting all rules validation messages except unique rule.问题是我收到了除唯一规则之外的所有规则验证消息。

So how to make unique rule work at client end?那么如何让唯一规则在客户端起作用呢?

What am I missing ?我错过了什么? Please help请帮忙

The only way is to enableAjaxValidation at client side唯一的方法是在客户端enableAjaxValidation

Here is doc about it 这是关于它的文档

To enable AJAX validation for a single input field, configure the enableAjaxValidation property of that field to be true and specify a unique form id:要为单个输入字段启用 AJAX 验证,请将该字段的 enableAjaxValidation 属性配置为 true 并指定唯一的表单 ID:

use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'registration-form',
]);

echo $form->field($model, 'username', ['enableAjaxValidation' => true]);

// ...

ActiveForm::end();

You also need to prepare the server so that it can handle the AJAX validation requests.您还需要准备服务器,以便它可以处理 AJAX 验证请求。 This can be achieved by a code snippet like the following in the controller actions:这可以通过控制器操作中的如下代码片段来实现:

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

Unfortunately, this has to come from DB's ActiveRecordSet on an update that's when it realizes this field is unique.不幸的是,这必须来自 DB 的 ActiveRecordSet 在更新时它意识到该字段是唯一的。 The easiest way is by doing a check if ($model->save()) is true otherwise return/render back the form and you will see a framework message that a particular field has been taken already.最简单的方法是检查 ($model->save()) 是否为真,否则返回/呈现表单,您将看到一个框架消息,表明特定字段已被占用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM