Home  >  Article  >  Backend Development  >  Detailed explanation of how Yii2 implements a custom independent validator

Detailed explanation of how Yii2 implements a custom independent validator

*文
*文Original
2018-01-03 11:36:442442browse

How to implement a custom independent validator in Yii2? This article mainly introduces the method of Yii2 to implement a custom independent validator, and analyzes the implementation and use of Yii2's custom independent validator in the form of examples. Friends in need can refer to it. I hope it will be helpful to everyone.

The example in this article describes the method of implementing a custom independent validator in Yii2. Share it with everyone for your reference, the details are as follows:

Create a new file:

<?php
namespace common\helps;
use yii\validators\Validator;
class ArrayValidator extends Validator
{
  public function validateAttribute($model, $attribute)
  {
    if (!is_array($model->$attribute)) {
      $this->addError($model, $attribute, $attribute . &#39;必须是一个数组&#39;);
    }
  }
}

When using:

public function rules()
{
  return [
    ...
    [&#39;kind_ids&#39;, &#39;common\helps\ArrayValidator&#39;], // 自定义验证
    ...
  ];
}

Related recommendations:

Solve the problem that Yii CFileCache cannot obtain the value

Yii2 integrates Xunsou to achieve efficient Chinese word segmentation retrieval

How Yii filters bad code

The above is the detailed content of Detailed explanation of how Yii2 implements a custom independent validator. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn