Zend 2表格验证员

时间:2014-09-02 08:49:54

标签: php forms validation zend-framework zend-framework2

我在Zend 2表单中设置了一些验证器,但是isValid总是返回true,忽略它们。转储整个表单对象,它看起来好像甚至没有附加验证器,这里是表单代码:

namespace UserManagement\Form;
use Zend\Form\Form;

class SearchUserForm extends Form
{
    public function __construct($name = null)
    {
        // we want to ignore the name passed
        parent::__construct('SearchUser');
        $this->setAttribute('method', 'post');
        $this->add(array(
            'name' => 'search',
            'attributes' => array(
                'type'  => 'text',
                'required' => true,
            ),
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name'    => 'StringLength',
                    'options' => array(
                        'encoding' => 'UTF-8',
                        'min'      => 4,
                        'max'      => 100,
                    ),
                )
            ),
        ));

然后在控制器中检查它是否有效:

        if( $this->getRequest()->isPost() )
        {

            $searchForm->setData( $this->params()->fromPost() );
            if( $searchForm->isValid() )
            {
                echo "yep";exit;
            }
            else
            {
                echo "nope";exit;
            }

尽管有1个字符的字符串长度,但始终输出'yep'。我实际上有这个工作,但将验证器放在一个单独的过滤器类中,并将其附加到表单 - 但我的问题是应该这项工作?

1 个答案:

答案 0 :(得分:1)

不,我不认为你在做什么会工作,正如你所说,你可以使用单独的输入过滤器。您还可以在表单上使用InputFilterProviderInterface,如下所示

<?php
namespace Test\Form;

use Zend\Form\Element;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class TestForm extends Form implements InputFilterProviderInterface
{    
/**
 * Provide default input rules for this element
 *
 * Attaches strip tags filter
 *
 * @return array
 */
public function getInputFilterSpecification()
{
    return [
        'search' => [
            'required' => true,
            'filters'  => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'),
        ),
        'validators' => array(
            array(
                'name'    => 'StringLength',
                'options' => array(
                    'encoding' => 'UTF-8',
                    'min'      => 4,
                    'max'      => 100,
                ),
            )
        ),
        ]
    ];
}



public function __construct()
{
    $this->add(array(
            'name' => 'search',
            'type' => 'Text',

    ));
}

}