zend form email validation

Bryan picture Bryan · Dec 17, 2010 · Viewed 27k times · Source

I have the following code to generate an input field for user's email address

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress')
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                                                        array(
                                                                'adapter'=>Zend_Registry::get('user_db'),
                                                                'field'=>'email',
                                                                'table'=>'tbl_user'
                                                                )))
    ->setRequired(true)
    ->setDecorators(array(
                            array('Label', array('escape'=>false, 'placement'=>'append')),
                            array('ViewHelper'),
                            array('Errors'),
                            array('Description',array('escape'=>false,'tag'=>'div')),
                            array('HtmlTag', array('tag' => 'div')),
                        ));
$this->addElement($email);

now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin@l' as email address, and the errors will be
* 'l' is no valid hostname for email address 'admin@l'
* 'l' does not match the expected structure for a DNS hostname
* 'l' appears to be a local network name but local network names are not allowed

I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.

Answer

Ivan Buttinoni picture Ivan Buttinoni · Mar 29, 2011

Well, it's a late answer but I think is always useful.

Simply add true as second param of addValidator()

From Zend docs (http://framework.zend.com/apidoc/1.8/):

addValidator (line 67)

Adds a validator to the end of the chain

If $breakChainOnFailure is true, then if the validator fails, the next validator in the chain, if one exists, will not be executed.

return: Provides a fluent interface

access: public

Here the signature:

Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])

Zend_Validate_Interface $validator
boolean $breakChainOnFailure

So the code is:

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress',  TRUE  ) // added true here
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                array(
                        'adapter'=>Zend_Registry::get('user_db'),
                        'field'=>'email',
                        'table'=>'tbl_user'
                        ), TRUE )
            );