zf2 validation form: How can I validate dependent fields?

chrvadala picture chrvadala · Oct 3, 2012 · Viewed 7.2k times · Source

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 ?

Answer

Andreas Linden picture Andreas Linden · Oct 3, 2012

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
    }
}