Yii Framework Forum: Validate attribute for type array - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Validate attribute for type array

#1 User is offline   GSTAR 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,058
  • Joined: 30-October 09

Posted 22 December 2017 - 06:11 PM

In Yii 1.1. we could use the following validation rule to ensure an attribute is of type array:

['category_ids', 'type', 'type' => 'array', 'message' => '{attribute} contains an invalid value.'],


I use this to ensure checkboxes are sent as an array, e.g:

<input type="checkbox" name="Form[category_ids][]" value="1">


However in Yii2 I can not find an equivalent validator. Does anyone know how to do this?
0

#2 User is offline   skworden 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 525
  • Joined: 14-June 12
  • Location:Virginia, USA

Posted 22 December 2017 - 07:33 PM

There isn't an array validator, however, there is a validator to ensure each item of the array is valid.
Each Validator
1

#3 User is offline   alrazi 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,546
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 23 December 2017 - 02:41 PM

you can write a custom validator here is an example of your array validator

// custom rule
['category_ids', 'validateArray'],


// and your custom validator
public function validateArray($attribute, $params, $validator)
{
    if (!is_array($this->$attribute)) {
        $this->addError($attribute, 'The attribute must be array.');
    }
}

1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users