Custom validation rule is not working for CFormModel

2k Views Asked by At

My front end is Php Yii. I am trying to create a custom validation rule which checks to see if the username already exists in the database.

I don't have 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 doesn't seem to work at all, I also tried this:

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

}

Even then, it doesn't seem to work. What am I doing wrong here?

2

There are 2 best solutions below

0
On

The problem with your code is that it doesn't return true or false.

Here is one of my rules to help you:

<?php
....
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, link', 'required'),
            array('title, link', 'length', 'max' => 45),
            array('description', 'length', 'max' => 200),
            array('sections','atleast_three'),

        );
    }
    public function atleast_three()
    {
        if(count($this->sections) < 3)
        {
            $this->addError('sections','chose 3 at least.');
            return false;
        }
        return true;
    }

...

?>
0
On

I met the same issue and finally got it solved. Hopefully, the solution could be useful for resolving your problem.

The reasons why the customised validation function is not called are:

  1. this is a server side rather than client side validation
  2. when you click the "submit" button, the controller function takes over the process first
  3. the customised function won't be involved if you didn't call "$model->validate()"

Therefore, the solution is actually simple:

Add "$model->validate()" in the controller function. Here is my code:

"valid.php":

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'alloc-form',
    'enableClientValidation'=>true,
    'clientOptions'=>array('validateOnSubmit'=>true,),
)); ?>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'valid_field'); ?>
    <?php echo $form->textField($model,'valid_field'); ?>
    <?php echo $form->error($model,'valid_field'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton('Submit'); ?>
</div>

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

"ValidForm.php":

class ValidForm extends CFormModel
{
    public $valid_field;

    public function rules()
    {
        return array(
            array('valid_field', 'customValidation'),
        );
    }

    public function customValidation($attribute,$params)
    {
        $this->addError($attribute,'bla');
    }
}

"SiteController.php"

public function actionValid()
{
    $model = new ValidForm;

    if(isset($_POST['AllocationForm']))
    {
        // "customValidation" function won't be called unless this part is added
    if($model->validate())
        {
            // do something
        }
        // do something
    }
}