yii2 custom validation rules

Without further ado, just go to the code






class AbcModel extends Model
{


    public $aaa;
    public $bbb;
    public $bbb;




    /**
     * Validate the submitted form
     *
     * @return array
     */
    public function rules()
    {
        return [
            // custom validation
            [['aaa', 'bbb', 'ccc'], 'customValidationCityCode'],
        ];
    }



    public function customValidationCityCode($attribute, $params)
    {
        if (!isset($this->$attribute)
            | | empty($this->$attribute)
            || !is_array($this->$attribute)
        ) {
            $this->addError($attribute, "The value is empty or does not exist or does not match the type.");
            return;
        }


    }
}

  The above code means that when (new Abc())->validate() is enabled, the properties will be validated according to the order of rules, and the custom validation method customValidationCityCode will call the customValidationCityCode method as many times as there are parameters that need to be validated. The parameter $attribute in the customValidationCityCode method corresponds to aaa bbb ccc respectively

 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728663&siteId=291194637