ZF2 Captcha validation ignored when using an input filter

别来无恙 提交于 2020-01-05 12:23:31

问题


I have a form in my ZF2 app with a CAPTCHA element as follows :

$this->add(array(
        'type' => 'Zend\Form\Element\Captcha',
        'name' => 'captcha',
        'attributes' => array(
            'class'=>'form-control',
        ),
        'options' => array(
            'label' => 'Please verify you are human.',
            'captcha' => array('class' => 'Dumb')
        ),
    ));

I have an input filter attached to the form that validates the other elements in the form (name, email, message). When this is attached to the form the validation for the CAPTCHA field is ignored when checking if valid.

if ($request->isPost()) {          
        // set the filter
        $form->setInputFilter($form->getInputFilter());
        $form->setData($request->getPost());
        if ($form->isValid()) { ...

If i remove the input filter then the CAPTCHA field is validated correctly but obviously the other fields have no validators. What silly mistake am I making? Is there a "CAPTCHA" validator I have to set in the input filter?


回答1:


The issue is because, I assume that on your form you have created a method called:

getInputFilter();

which overrides the original getInputFilter(),

there are two solutions:

rename your function on your form to be getInputFilterCustom()

and then modify also:

if ($request->isPost()) {          
    // set the filter
    $form->setInputFilter($form->getInputFilterCustom());

or inside your current getInputFilter() add the logic to validate the captcha.




回答2:


This is my code to add a captcha image control in a ZF2 form :

        $this->add(array(
                'name' => 'captcha',
                'type' => 'Captcha',
                'attributes' => array(
                        'id'    => 'captcha',
                        'autocomplete' => 'off',
                        'required'     => 'required'
                ),
                'options'    => array(
                        'label' => 'Captcha :',
                        'captcha' => new \Zend\Captcha\Image(array(
                            'font' => 'public/fonts/arial.ttf',
                            'imgDir' => 'public/img/captcha',
                            'imgUrl' => 'img/captcha'               
                        ))
                ),
        ));

The others form elements are using validators from the input filter, but i didn't use any validators to make it work.

I hope this can help you.




回答3:


It is because you don't call the parent getInputFilter() within yours. Simply do

public function getInputFilter()
{
    parent::getInputFilter();

    //... your filters here
}


来源:https://stackoverflow.com/questions/24778339/zf2-captcha-validation-ignored-when-using-an-input-filter

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