ZF2 : Priority for Validators in InputFilter

2019-07-19 06:29发布

I have a validator on a form entry like this :

    $this->add(array(
        'name' => 'email',
        'required' => true,
        'filter' => array(
            'name' => 'StripTags',
        ),
        'validators' => array(
            array(
                'name' => 'NotEmpty',
                'options' => array(
                    'messages' => array(
                        \Zend\Validator\NotEmpty::IS_EMPTY => 'Veuillez renseigner une adresse e-mail.',
                    ),
                ),
            ),                
            array(
                'name' => 'StringLength',
                'options' => array(
                    'encoding' => 'UTF-8',
                    'min' => 1,
                    'max' => 100,
                ),
            ),
            array(
                'name' => 'EmailAddress',
                'options' => array(
                ),
            ),
        ),
    ));

There's basicaly 3 validators on my input. The NotEmpty, the StringLength, and the EmailAdress.

Is there any way to set a kind of priority between them ? Right now, if I submit an empty form, I get messages relative to those 3 validators, ie. :

  • My input is empty.
  • My string length is too short (thanks...)
  • My input is not an email (thanks again...)

Is there anyway to tell my validator to stop at the first failure ? (or at least to only print the 1st message).

1条回答
贪生不怕死
2楼-- · 2019-07-19 07:20

Use the 'break_chain_on_failure' key in your validator spec with a value of true, ie

$this->add(array(
    'name' => 'email',
    'required' => true,
    'filter' => array(
        'name' => 'StripTags',
    ),
    'validators' => array(
        array(
            'name' => 'NotEmpty',
            'break_chain_on_failure' => true,
            'options' => array(
                'messages' => array(
                    \Zend\Validator\NotEmpty::IS_EMPTY => 'Veuillez renseigner une adresse e-mail.',
                ),
            ),
        ),                
        array(
            'name' => 'StringLength',
            'break_chain_on_failure' => true, 
            'options' => array(
                'encoding' => 'UTF-8',
                'min' => 1,
                'max' => 100,
            ),
        ),
        array(
            'name' => 'EmailAddress',
            'options' => array(
            ),
        ),
    ),
));
查看更多
登录 后发表回答