How to validate unique field on client-side?

Hi, there!

I need to show if user name is not unique by ajax request (before user submit registration form).

How can i do that using validation rules and activeform?

array('username', 'unique', 'message' => UserModule::t("This user's name already exists."))

rule works, but only when user’s submited form

i’ve tried bind own onchange-event on input field.

When I send ajax-request to specify action, it also works

$item = new User;

$item->username = $login;

if (!$item->validate('username',$login))


  if ($item->hasErrors())



i get ‘duplicate user’ error by validator!

But when i try to show it in error-field it seems conflict with activeform onchange-event function and not appears

tried options:

'on'=>'scenario'... 'enableClientValidation' => true...

not working :(

has a solution?

This is actually built into Yii already. You don’t really need to create any custom code for it.

  1. Create model + CRUD using gii.

  2. Ensure model has unique validator.

array('username', 'unique', 'message' => UserModule::t("This user's name already exists."))

  1. Go into CRUD controller and uncomment ajax validation.

// Uncomment the following line if AJAX validation is needed


  1. Go into view file _form.php and enable ajax validation.

<?php $form=$this->beginWidget('CActiveForm', array(




)); ?>

It’s clear…

Ajax validation is working

I need ajax validation of username (check unique rule) working before submit

Strange, but only this rule not responde on ‘change’ event.

Other rules are working!

array('username', 'unique', 'message' => UserModule::t("This user's name already exists.")),

array('username', 'length', 'max'=>20, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 20 characters).")),

array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => UserModule::t("Incorrect symbols (A-z0-9).")),

After form submitted unique-rule also working!

What could be wrong?

Has anybody found a solution for that?

Hi any solution im also stuck with the same

In controller, action create() check the code like this

$model=new User; 


also check the ajax validation function

protected function performAjaxValidation($model)


		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')


			echo CActiveForm::validate($model);




Post your complete rules.


Hi ,

Issue resolved :)

Great…!! How it solve?


Actually one of the model form element was not defined properly .

When i fixed that then both ajax and client validation worked properly as specified in the above posts.


Good… :)

For others who may also have a problem with the validation:

I use 2 different models in 1 form. Here the ajax validation function looks as follows:

if(isset($_POST['ajax']) && $_POST['ajax']==='user-form') {

	echo CActiveForm::validate(array($model1, $model2));



Maybe this helps ;)