Custom Validation Rule Is Not Working For My Cformmodel

I am trying to create a custom validation rule which checks if username is already exists in the database.

I dont have a direct access to the database. I have to use the RestClient to communicate with the Database…

My issue is that custom validation rule is not working with my CFormModel

here is my code




    public function rules()

    { 

      return array(


        array('name', 'length', 'max' => 255),

        array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/' )

        array('nickname','alreadyexists'),  

      );

    }


    public function alreadyexists($attribute, $params)

    {

        $result = ProviderUtil::CheckProviderByNickName($this->nickname);

            if($result==-1)

            {

            $this->addError($attribute,'This Provider handler already exists. Please try with a different one.');

            }

    }

This doesnt seems to work to all, I tried this also to check if the control is coming there,


public function alreadyexists($attribute, $params)

{

            $this->addError($attribute,'This Provider handler already exists. Please try with a different one.');


}

but these too didnt work. Am i doing anything wrong here?

Hi

what is the class ProviderUtil and method CheckProviderByNickName ?

why didn’t use the validator ‘unique’ ?


...

array('nickname','unique'),  

Can you show the code from your action? It sounds like validation isn’t being triggered.

EDIT

Your rules method is wrong, it should be in the following format:




    public function rules()

    {

        return array(

            array(...),

            ...

        );

    }



You’re not returning the validation array.

I absolute agree!

ProviderUtil is one of my Component, it is used to communicate with my backend(its in java). i dont have direct access to database since i am restClient. so i cannot use ‘unique’.

Sorry!! that was my mistake when copyinng code here… i have corrected it. my all other rules is working. only "alreadyexists" is not working

Should return something in the validation code?


public function alreadyexists($attribute, $params)

    {

        $result = ProviderUtil::CheckProviderByNickName($this->nickname);

            if($result==-1)

            {


            $this->addError($attribute,'This Provider handler already exists. Please try with a different one.');

return false;

            }

return true;

    }

check the returned value in result… is it -1 ?

Yes, it is -1. even this didnt work.


public function alreadyexists($attribute, $params)

{

            $this->addError($attribute,'This Provider handler already exists. Please try with a different one.');


}

Can you post the exact code from your rules() method and from your action?

view


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

		'id' => 'provider-profile-form',	

		'method' => 'POST',

		'enableClientValidation' => true,

		'clientOptions' => array(

		'validateOnSubmit' => true,

		

		)));


?>


 <div class="grid_8">

                <div class="grid_8"><?php echo $form->labelEx($model, 'name'); ?></div>

                <div class="grid_8"><?php echo $form->textField($model, 'name', array('class' => 'prov_provider_field')); ?>

                <?php echo $form->error($model, 'name'); ?> </div>


                <div class="grid_8"><?php echo $form->labelEx($model, 'nickname'); ?></div>

                <div class="grid_8" style="margin-bottom: 15px;"><?php echo $form->textField($model, 'nickname', array('class' => 'prov_provider_field')); ?>

                <?php echo $form->error($model, 'nickname'); ?> </div>

                <input type="submit"  value="submit">

<?php $this->endwidget(); ?>

</div>

</div>

my model


class ProviderProfileForm extends CFormModel

{

	

	public $name;

	public $nickname;

public function rules()

	{

		return array(

			array('name', 'required', 'message' => 'Business/Individual name cannot be blank'),

			array('name', 'length', 'max' => 255),

			//array('nickname', 'length', 'max' => 25),

			array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/' ),

		

			array('nickname','alreadyexists','on'=>'insert'),

                           )

       }

public function alreadyexists($attribute, $params)

	{

			$result = ProviderUtil::CheckProviderByNickName($this->nickname);

				if($result==-1)

				{

				$this->addError($attribute,'This Provider handler already exists. Please try with a different one.');

				//console.log("control is here");

				return false;

				}

	}

}

//mycontrolleraction


 public function actionIndex()

	{

	$model = new ProviderProfileForm();

	$model->setScenario('insert');

	$this->render('index',array('model'=>$model));

	}

I bet you forgot to set scenario in your create action.

I suspect that the errors you are seeing are from client validation. Try disabling that while you debug the problem.

What do u mean?

Is this not enough ?


$model = new ProviderProfileForm();

        $model->setScenario('insert');

@Keith … after disabling client validation , the validation errors are not coming at all…

So do you mean enable client validation will not apply for custom validations ?

I mean I don’t see the actual saving code, so if your form is being displayed in actionIndex, and form’s action points to, say, actionCreate, you’ll have to set scenario in actionCreate too.

But Keith is right, it’s all about client validation, because you’re probably not submitting the form at all.

As mentioned above, you seem to be posting back to your index action, and there’s no code in there to save the model. Your form will post back to the current action by default unless you override it.

hi

this work :

in view :




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

    'id' => 'login-form',

    'enableAjaxValidation'=>TRUE,

    'enableClientValidation'=>true,

    'clientOptions'=>array(

	'validateOnSubmit'=>true,

        

	),

    ));



in action :




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

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}