Unique validator


Is there a way to use user validation on ‘unique’ rules in forms ?


What do you mean? What would you like to do?

When a user input something in a field that is supposed to be unique, display a error message like ‘this username is already taken’ without submitting the form.

Submitting is required because only server has the info you need but you can use AJAX for this.

Check this section.

I did that and firebug show the correct JSON answer, but how do I display the error in my page?

Are you using ActiveForm widget? With the configuration and code snippet mentioned at the end of the this guide section error messages should be displayed automatically.


here is the form :

<?php $form = ActiveForm::begin([

    	'id' => $model->formName(),

    	'validationUrl' => ['/commandes/ajaxvalid'],

    	'enableClientValidation' => true,

		'options' => ['class' => 'form-horizontal'],

		'fieldConfig' => [

            'template' => "{label}<div class=\"col-lg-6\">{input}</div><div class=\"col-lg-4\">{error}</div>",

            'labelOptions' => ['class' => 'col-lg-2 control-label'],


	]); ?>

<?= $form->field($model, 'num_de_serie' ,['enableAjaxValidation' => true, 'validateOnChange' => false])->textInput(['maxlength' => '15' , 'id' => 'numero_de_serie']) ?>

The controller:

public function actionAjaxvalid ()


		$model = new Commandes();

		if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

			Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

			return ActiveForm::validate($model, ['num_de_serie']);



You are overriding field ID (‘id’ => ‘numero_de_serie’) and I guess validation js looks for default ‘commandes-num_de_serie’ and this is probably why no error message is displayed.

Don’t override the field ID or configure everything to work with overriden one.

That worked.

Thanks a lot.