zend-framework2zend-validatezend-framework3

How to check for duplicate email entries while registering new users in zend framework 3


I want to duplicate email validation to registration page.For now the following validation is implemented on email.

$inputFilter->add(array(
             'name'     => 'email',
             'required' => true,
             'filters'  => array(
                 array('name' => 'StripTags'),
                 array('name' => 'StringTrim'),
             ),
             'validators' => array(
                 array(
                     'name' => 'NotEmpty',
                     'options' => array(
                        'messages' => array(
                            $isEmpty => 'Email can not be empty.',
                         ),
                     ),
                    'break_chain_on_failure' => true
                 ),
                 array(
                     'name' => 'EmailAddress',
                     'options' => array(
                        'messages' => array(
                            $invalidEmail => 'Enter Valid Email Address.'
                        )
                    )
                )
              )
             )
          );

Solution

  • If I understand correctly, you do not want the email to be duplicated.

    You can add the Zend\Validator\Db\NoRecordExists validator :

        'validators' = array(
        array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    $isEmpty => 'Email can not be empty.',
                ),
            ),
            'break_chain_on_failure' => true
        ),
        array(
            'name' => 'EmailAddress',
            'options' => array(
                'messages' => array(
                    $invalidEmail => 'Enter Valid Email Address.'
                )
            )
        ),
        array(
            'name' => 'Zend\Validator\Db\NoRecordExists',
            'options' => array(
                'table' => 'your_table_name',
                'field' => 'email',
                'adapter' => 'your_db_adapter'
            )
        )
    )
    

    You should not forget to inject your $db_adapter into your form.