Input Validation In Yii Model

How to Create Custom Input Validation Rules in Yii Model for Dependent Input Field?

Suppose we want to create a dependent input validation rule in Yii model for dependent 2 input fields. Field one is status and field two is reason. If user select a status from dropdown list then they must be fill-up reason field. If not then it will show an error message.

In model rules-

public function rules()
{
   return array(
   array(...),
   array(...),
   array('status', 'reasonValidators'),
  );
}

And validation function-

public function reasonValidators()
{
  if ((int)$this->status=="Yes")
  {
    $labels = $this->attributeLabels(); // Getting labels of the attributes
    if($this->reason=="")
    {
       $this->addError("reason", $labels["reason"]." cannot be blank.");
    }
    // More dependent on type can be written here
  }
}

Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *