Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate a registration form in zend framework 2?

i am trying to validate a user registration form in Zend Framework 2.

More specifically how to validate the email, ZF1 i could do:

$email->setValidators( array(new Zend_Validate_EmailAddress()) );

I'm wondering if i can just call something similar like this.

Also I'm wondering how to validate two fields that need to be the same like the password field and the password verification.

I guess that when i say if($form->isValid()).. this will check the getInputFilter() method for all validation.

I've been taking a look at ZfcUser module but, right now, i can't understand much since i don't have a full grasp on how ZF2 works

Any ideas, maybe a simple example?

thanks

like image 897
Patrioticcow Avatar asked Jan 16 '23 08:01

Patrioticcow


2 Answers

Have you read the official tutorial to see how the new ZF2 Form component works?

At a very high level, you need a Form object and a Filter object working together. The Filter object is where you place your filters and validators. However, if you use a form element of type EmailAddress in your Form, then it will automatically add the correct validator. There is more information in the manual.

I recently did a webinar on forms for Zend which you should be able to find on this page.

like image 119
Rob Allen Avatar answered Jan 20 '23 16:01

Rob Allen


i've figure it out.

the validators are multidimensional arrays and each array has a name and some options. It might be a bit wired in the beginning to notice it, but much configuration in zf2 is in this way

see an example for the password:

$inputFilter->add($factory->createInput([
            'name' => 'password',
            'required' => true,
            'filters' => [ ['name' => 'StringTrim'], ],
            'validators' => [
                [
                    'name' => 'StringLength',
                    'options' => [
                        'encoding' => 'UTF-8',
                        'min'      => 6,
                        'max'      => 128,
                    ],
                ],
            ],
        ]));

        $inputFilter->add($factory->createInput([
            'name' => 'password_verify',
            'required' => true,
            'filters' => [ ['name' => 'StringTrim'], ],
            'validators' => [
                array(
                    'name'    => 'StringLength',
                    'options' => array( 'min' => 6 ),
                ),
                array(
                    'name' => 'identical',
                    'options' => array('token' => 'password' )
                ),
            ],
        ]));

note, in php 5.3 > an array could be written like array() or [], in the above example i mix them up for no particular reason.

like image 38
Patrioticcow Avatar answered Jan 20 '23 15:01

Patrioticcow