Zend Framework 2-使用验证器构建简单表单 [英] Zend Framework 2 - Building a simple form with Validators

查看:46
本文介绍了Zend Framework 2-使用验证器构建简单表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个非常简单的表单,并希望在表单本身中添加验证.以大约3行的形式添加时,不需要一百万行代码.

I'm trying to build a VERY simple form and want to add the validation in the form itself. No need for million lines of code when adding it in the form just is about 3 lines.

这是我的两个领域:

$this->add(array(
        'name' => 'username',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'Name*',
            'required' => true,
        ),
        'filters' => array(
            array('StringTrim')
        ),
    ));
$this->add(array(
        'name' => 'email',
        'attributes' => array(
            'type'  => 'text',
        ),
        'options' => array(
            'label' => 'E-Mail*',
            'required' => true,
        ),
        'validators' => array(
            array('regex', true, array(
                'pattern'   => '/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i',
                'messages'  =>  'Bitte eine gültige E-Mailadresse angeben'))
        ),
        'filters' => array(
            array('StringTrim')
        ),
    ));

$ form-> isValid()始终返回true.即使该字段为空.我还有另一个带有正则表达式验证器的字段,同样的东西……WTF,Zend?

The $form->isValid() ALWAYS returns true. Even if the field is empty. I have another field with a regex-validator, same thing... WTF, Zend?

我的控制器如下:

$form = new UserForm();
    $form->setHydrator(new DoctrineEntity($entityManager));

    $request = $this->getRequest();
    if ($request->isPost()) {
        $backenduser = new User();
        $form->bind($user);
        $form->setData($request->getPost());

        if ($form->isValid()) {
             ....
        }

有什么想法吗?

推荐答案

验证和过滤定义不是Form本身的一部分.参见 http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html

Validation- and Filtering-Definitions aren't part of the Form itself. See http://framework.zend.com/manual/2.0/en/user-guide/forms-and-actions.html

这篇关于Zend Framework 2-使用验证器构建简单表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆