Zend Framework 2 - Building a simple form with Validators

眉间皱痕 提交于 2019-12-12 21:51:29

问题


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.

Here are two of my fields:

$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')
        ),
    ));

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

My controller looks like this:

$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()) {
             ....
        }

Any ideas?


回答1:


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




回答2:


Try this, pass $_POST data.

 if($form->isValid($_POST)) {
     // success!
  } else {
     // failure!
  }


来源:https://stackoverflow.com/questions/14212050/zend-framework-2-building-a-simple-form-with-validators

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