zf2 validation form: How can I validate dependent fields?
Asked Answered
S

2

5

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 ?

Savate answered 3/10, 2012 at 10:52 Comment(0)
B
17

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
    }
}
Bloodred answered 3/10, 2012 at 14:9 Comment(2)
thank you! it works, but how can I register this translator in ValidatorPluginManager?Savate
dunno, not using this, but you can just pass the full classname (string) as name for the validator in an input specificationBloodred
A
0

Craft your own solution using the Callback validator.

Examples are here: http://packages.zendframework.com/docs/latest/manual/en/modules/zend.validator.set.html#callback

Autacoid answered 4/10, 2012 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.