How To Write Custom Validation Rule In Yii

How To Write Custom Validation Rule In Yii

In this example we’ll be explaining how you can write a custom rule to validate a json with specific keys using mongo document. 

Create a Model in Yii

Let us take an example of employee collections which has fields value as name, title, age and designation. For creating a model in yii we will extend an ActiveRecord class and specify our field names and rules.

class Employee extends \yii\mongodb\ActiveRecord
{
    private $expectedUserKeys = ['name','title','age','designation'];
 
 ...
 ...
 }

Write Your own Custom Method.

Here we have used a BaseJson helper provided by yii to decode the json into array. To use this helper class add use yii\helpers\BaseJson to include the helper class in your model class.

public function jsonValidate($attribute, $params)
  {        
      if($this->isJson($this->{$attribute})) {
          $jsonArr = BaseJson::decode($this->{$attribute}, $asArray = true);                     
              if(array_keys($jsonArr) != $params) {                
                      $this->addError($attribute, 'Invalid Keys');
                      return false; 
                  }
              return true;
      }
      $this->addError($attribute, 'Invalid Json');
      return false;
  } 
    
public function isJson($string) 
  {
      $data = json_decode($string);
      return (json_last_error() == JSON_ERROR_NONE) ? true : false;
  }

Add Your Custom Validation Function to Rules

Now we will add our custom validation method to employee model.

public function rules()
    {
        return [
                    ['user', 'required'],
                    ['user', 'jsonValidate', 'params' => $this->expectedUserKeys]
                ];
    }

Using['user', 'jsonValidate', 'params' => $this->expectedUserKeys] , this will call the custom function jsonValidate and passes the parameters: $attribute = 'user' and $params = $expectedUserKeys. In this way if your json is invalid or if it does not matches the given set of keys, it will throw the specified error while inserting or updating the data. The jsonValidate() method we have created can be used dynamically, you just need to define an array and pass the array in the rule with attribute to validate your json field as shown in above code snippet.

Leave a Comment