Walllter
Walllter

Reputation: 350

Validation Form in ZF2

How i can a validate input data in my from email and password fields, if email field must contains only valid E-mail address and password between 6 and 12 length characters? My form code:

namespace Notes\Form;

use Zend\Form\Form;
use Zend\InputFilter\InputProviderInterface;
use Zend\InputFilter\InputFilter;
use Zend\Validator\ValidatorInterface;
use Zend\InputFilter\Factory as InputFactory;



class AuthorizationForm extends Form
{
    public function __construct($name = null)
     {
     parent::__construct('auth');
     $this->setAttribute('method', 'post');

     $this->add(array(
         'name' => 'email',
         'attributes' => array(
             'type'  => 'text',
             'style' => 'width: 250px;',
         ),
     ));

    $this->add(array(
        'name' => 'password',
        'attributes' => array(
            'type'  => 'password',
            'style' => 'width: 250px;',
         ),
    ));

    $this->add(array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Login',
            'id' => 'submitbutton',
            'class' => 'fbutton green',
            ),
    ));

     $this->add(array(
         'type' => 'Zend\Form\Element\Checkbox',
         'name' => 'save_login',
         'options' => array(
             'label' => 'Remember me ',
             'checked_value' => '1',
         ),
     ));
   }
}

Thanks for answers!

Upvotes: 0

Views: 205

Answers (2)

Ronak K
Ronak K

Reputation: 1567

There is inbuilt validator for email validation that will go like this,

'validators' => array(                     
            array('EmailAddress',true)                
             )

also for more detailed information visit the following, http://zend-framework-community.634137.n4.nabble.com/ZF2-How-to-validate-a-password-and-email-in-zend-framework-2-td4657533.html

Upvotes: 1

KumarA
KumarA

Reputation: 1378

Add these validators into your Model file:

  // For email validation
    'validators' => array(
        array('regex', true, array(
            'pattern'   => '/[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i',
            'messages'  =>  'Your error message here...'))
    ),

  // For character length validation
    'validators' => array(
          array(
              'name' => 'Between',
              'options' => array(
                  'min' => 6,
                  'max' => 12,
              ),
          ),
        ),

I hope this helps.

Upvotes: 1

Related Questions