Ticket Details
Validation Error - Multiple Select
ENHANCEMENT Ticket (closed)
###What happened: - When using the default validation rules, I experienced the following error: Warning: preg_match() expects parameter 2 to be string, array given in /home/caen_master/clickandeatnow.com/libraries/lithium/util/Validator.php on line 612 The issue is that I was trying to check to make sure the user had selected at least one value from a multiple select box. ###What was expected: The validation should have recognized that the field was an array and split it up.
A quick update to this ticket. The general problem is, that the validator always assumes that you pass a string and not an array. Here's a general purpose failing test case: {{{ public function testNotEmptyWithArray() { $data = array('foo', 'bar'); $result = Validator::isNotEmpty($data); $this->assertTrue($result); $result = Validator::isAlphaNumeric($data); $this->assertTrue($result); } }}} In the current implementation, the validator assumes a string for $value in preg_match: {{{ $regexPassed = (is_string($check) && preg_match($check, $value)); }}} Based on my current knowledge, i don't think that parsing an array as a value is covered in the validator (i also did not find any test cases for that). Writing a solution would be easy, but i think some discussion has to be done first: - what is the best way to implement it? just check before the preg_match if value is an `array()` and then do the check for each element? - we also need to decide what not empty means in this case: the actual $value is empty() and/or if there are elements in it that are empty? If we come up with a solution I'd be happy to implement it. Regards, MikeOf course, you can achieve this with custom validation rules and callbacks, here are some examples Simple check if the array is empty: {{{ public function testNotEmptyArray() { Validator::add('notEmptyArray', function($value) { return !empty($value); }); $emptyArray = array(); $notEmptyArray = array('foo', 'bar'); $this->assertFalse(Validator::isNotEmptyArray($emptyArray)); $this->assertTrue(Validator::isNotEmptyArray($notEmptyArray)); } }}} More advanced to check if the array is empty or one of the elements in the array is empty. Of course, this are only reference implementations and can be modified to the needs of the app: {{{ public function testNotEmptyNestedArray() { Validator::add('notEmptyNestedArray', function($value) { $valid = true; if(empty($value)) { $valid = false; } else { foreach($value As $k => $v) { if(empty($v)) { $valid = false; } } } return $valid; }); $emptyArray = array(); $notEmptyArray = array('foo', 'bar'); $emptyNestedArray = array('foo' => array()); $this->assertFalse(Validator::isNotEmptyNestedArray($emptyArray)); $this->assertTrue(Validator::isNotEmptyNestedArray($notEmptyArray)); $this->assertFalse(Validator::isNotEmptyNestedArray($emptyNestedArray)); } }}}