繁体   English   中英

数组的Yii2验证规则

[英]Yii2 validation rule for array

我在模型中有一个属性,希望以这种方式进行验证-它必须是一个数组,并且必须具有3个元素,而且数组中的每个元素都必须是一个字符串。 目前我正在使用。

['config', 'each', 'rule' => ['string']]

您可以简单地使用自定义验证器,例如:

['config', function ($attribute, $params) {
    if(!is_array($this->$attribute) || count($this->$attribute)!==3){
         $this->addError($attribute, 'Error message');
    }
}],
['config', 'each', 'rule' => ['string']]

阅读有关创建验证器的更多信息。

您可以添加custom validation规则,如下所示:

public function rules()
{
    return  ['config','checkIsArray'];
}

public function checkIsArray($attribute, $params)
{
    if (empty($this->config)) {
        $this->addError('config', "config cannot be empty");
    }
    elseif (!is_array($this->config)) {
        $this->addError('config', "config must be array.");
    }
    elseif (count($this->config)<3) {
        $this->addError('config', "config must have 3 elements");
    }
    else {
        foreach ($this->config as $value) {
            if (!is_string($value)) {
                $this->addError('config ', "config should have only string values.");
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM