Zend Framework 2 - Building a simple form with Val

2019-07-19 09:58发布

问题:

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!
  }