ZF2 : Priority for Validators in InputFilter

一世执手 提交于 2019-12-12 17:27:16

问题


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:


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(
            ),
        ),
    ),
));


来源:https://stackoverflow.com/questions/16841376/zf2-priority-for-validators-in-inputfilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!