I've an attribute in model which I want to validate in such a way that - It must be an array and must have 3 element, also every element inside array must be a string. Currently I'm using.
['config', 'each', 'rule' => ['string']]
You could simply use a custom validator, eg :
['config', function ($attribute, $params) {
if(!is_array($this->$attribute) || count($this->$attribute)!==3){
$this->addError($attribute, 'Error message');
}
}],
['config', 'each', 'rule' => ['string']]
Read more about creating validators .
You can add a custom
validation
rules like below:
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.");
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.