[英]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.