如何在Zend Framework 2表单中验证Captcha FIRST?

时间:2014-03-23 06:05:44

标签: php zend-framework2

如果Captcha失败,我想跳过验证表单中的其他元素。我知道那里有一个break_chain_on_failure变量,但找不到关于如何为Captcha设置它的文档

例如,在给定此表格的情况下,如何首先进行验证码验证?

class Registration extends Form implements InputFilter\InputFilterProviderInterface
{

    public function __construct()
    {
        parent::__construct('registration');

        /*
         * Phone
         */
        $phone = new Element\Text('phone');
        $phone->setLabel( "Phone")
            ->setAttribute( 'class', 'form-control bfh-phone' )
            ->setAttribute( 'data-format', '(ddd) ddd-dddd' );
        $this->add( $phone );


        /*
         * CAPTCHA
         */
        $theme          = 'clean';
        $locale         = isset( $_COOKIE['locale'] ) ? $_COOKIE['locale'] : 'en_US';
        list( $lang,  ) = explode( "_", $locale, 2 );

        $recaptcha = new Captcha\ReCaptcha();
        $recaptcha
            ->setOption( 'theme', $theme )
            ->setPubKey( '6Ld-&hl='.$lang)
            ->setPrivKey( '6Ld-' )
            ->setMessage( _( "Correctly repeat the text in the image, in the box beneath it" ) );



        $captcha = new Element\Captcha( 'captcha' );
        $captcha->setCaptcha( $recaptcha )
            ->setLabel( 'Please verify that you are human' );
        $this->add( $captcha );

    }

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

事实证明,你不能通过传统手段来做到这一点; Captcha元素为自己分配了自己的验证器,因此典型的验证器块不能成立。您可以在默认的Filter工厂中看到这一点,如果它是ValidatorInterface的实例,它会跳过整个breakOnFailure赋值。解决这个问题的方法是通过DI:

将ValidatorManager和FilterManager添加到我的表单中

这是我的表单对象的构造函数

public function __construct( AuthenticationFormInterface $authentication, Array $config, $filter_manager, $validator_manager )
{
    parent::__construct('registration');

    $chain  = new FilterChain();
    $chain->setPluginManager($filter_manager);
    $this->getFormFactory()
        ->getInputFilterFactory()
            ->setDefaultFilterChain( $chain );

    $chain  = new ValidatorChain();
    $chain->setPluginManager( $validator_manager );
    $this->getFormFactory()
        ->getInputFilterFactory()
            ->setDefaultValidatorChain( $chain );

工厂看起来像这样

'FooForm' => function( $sm ){
                $config = $sm->get('config');
                $form   = new \LDP\Form\Registration( $sm->get('LDP\Service\Authentication'), $config['launchfire-app']['registration'], $sm->get('FilterManager'), $sm->get('ValidatorManager') );
                return $form;
            },

在我使用它的控制器中,我在isValid()

之前添加了这一行
$form->getInputFilter()->get('captcha')->setBreakOnFailure( true );

现在,它首先验证并在失败时中断。