1

I have following rule for email to be unique in modal

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

I am not using ajax to submit form. 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

Maksym Semenykhin
  • 1,924
  • 15
  • 26
alwaysLearn
  • 6,882
  • 7
  • 39
  • 67

2 Answers2

3

The only way is to enableAjaxValidation at client side

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:

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. 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);
}
Maksym Semenykhin
  • 1,924
  • 15
  • 26
  • When I add code like this .. clientside validations stop working .On submit it takes me to the server without any validation – alwaysLearn Jul 08 '16 at 06:53
  • provide full php js html code and we will help you with it – Maksym Semenykhin Jul 08 '16 at 06:59
  • You must overwrite `clientValidateAttribute` function before use ajaxValidation. Link: [http://www.yiiframework.com/doc-2.0/guide-input-validation.html#deferred-validation](http://www.yiiframework.com/doc-2.0/guide-input-validation.html#deferred-validation) – ThanhPV Jul 08 '16 at 08:59
0

Unfortunately, this has to come from DB's ActiveRecordSet on an update that's when it realizes this field is unique. 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.