How to set error message from Ajax validation

I don’t know the best way to do this,

i want to check if a username already

exists in the database and i want to

do it on the fly (ajax, onChange):

I have a CActiveForm widget with a username field:


        <div class="span-4">

            <?php echo $form->labelEx($u,'username'); ?>

        </div>

        <div class="span-4">

            <?php echo $form->textField($u,'username'); ?>

        </div>

        <div class="span-4 last">

            <?php echo $form->error($u,'username'); ?>

        </div>

Since the CUniqueValidator doesn’t support client validation, i tried to

create my own validator to do this:


class UniqueAjaxValidator extends CUniqueValidator {

    

    public function clientValidateAttribute($object,$attribute)

    {

        //check database for username

        //if alreayd exists do:

        $js = "messages.push('".CJSON::encode($msg)."');";

        return $js;

}

But i dont know how to get the current value of the input field.

So far i only was able to get the input field value in Javascript

but when i did it in JavaScript and checked the existing of the

username like this:


$.getJSON(url+params,function (data) { messages.push(data); });

Somehow messages.push did not work in the success function.

help is much appreciated :)

CUniqueValidator should work out of the box in ajax validation.

Just try enabling ajax validation of the active form. :)

http://www.yiiframework.com/doc/api/1.1/CActiveForm#enableAjaxValidation-detail

sorry i mean ajax client validation, according to http://www.yiiframework.com/doc/api/1.1/CActiveForm

client validation for CUniqueValidator is not supported so far.

You are right. CUniqueValidator can not be performed with a simple client side script, because it has to access the db to check if the input value is unique in the table.

So, we have to use ajax.

And CActiveForm supports ajax validation for all the validators.

Couldn’t we enable both AjaxValidation and ClientValidation at the same time?

@softark yes it works. Of course, one has also to enable Ajax validation in the controller action


$this->performAjaxValidation($model);

Both [font=“Courier New”]enableAjaxValidation[/font] and [font=“Courier New”]enableClientValidation[/font] can be set to true in the view if we want to benefit from client validation first, then ajax validation (if a field fails to validate on the client side, it’s not re-validated on server-side afaik).

@softark i already had both enabled but somehow didn’t get the result i wanted

i was missing what bennouna said, in my controller i don’t even have the performAjaxValidation

function, copied it from a crud controller and added the call to my controller

no it works like a charm

thanks to both of you