Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zf2 validation form: How can I validate dependent fields?

I have 5 text form

$number1 = new Text('number-1');
$number2 = new Text('number-2');
$number3 = new Text('number-3');
....

with the relative filters

foreach(...)
   $input = new Input($elementName);
   $validator = new ValidatorChain();
   $validator->addByName('Int')
       ->addByName('Between', array(
          'min'=>0,
          'max'=>$this->maxAllowedTicket,
          'inclusive'=>true));
   $filter = new FilterChain();
   $filter->attachByName('Int');

   $input->setValidatorChain($validator);
   $input->setFilterChain($filter);

I would that only one of this 3 forms can contain a value different from 0. There are then two possible errors.

TOO MANY NUMBERS

 $data['number1'] = 5;
 $data['number2'] = 5;
 $data['number3'] = 0;
 $data['number4'] = 5;
 $data['number5'] = 0;

NO NUMBER

 $data['number1'] = 0;
 $data['number2'] = 0;
 $data['number3'] = 0;
 $data['number4'] = 0;
 $data['number5'] = 0;

How can I validate this multiple fields at the same time ?

like image 865
chrvadala Avatar asked Oct 03 '12 10:10

chrvadala


1 Answers

You need to write your own Validator class to do so. The isValid() method of your new validation class also receives the $context which includes the values of the whole form. This way you can validate the value of each field depending on the other fields.

namespace My\Validator;
use Zend\Validator\AbstractValidator;

class CustomValidator extends AbstractValidator
{
    public function isValid($value, $context = null)
    {
        // put your logic here and call
        // $this->error(); if required
    }
}
like image 194
Andreas Linden Avatar answered Oct 10 '22 07:10

Andreas Linden