Saturday
8
August
2009

Validating emails

Validating emails can be a tricky task.
Zend Framework has a own validator for this problem.

Zend_Validate_EmailAddress

And there is another thing to know… emails consist of 2 different parts… the address part and the hostname part. As you may imagine the hostname part is checked by a own validator… Zend_Validate_Hostname.

These things are done in background, so you will not have any notification of this. No problem until now… but what to do when you want to set your own validation messages ?

You would have to setup a own hostname validator, set your messages within it, and attach it to the email validator… example:

$hostname = new Zend_Validate_Hostname();
$hostname->setMessages(
    array(
        Zend_Validate_Hostname::UNKNOWN_TLD => 'I don't know your TLD',
        Zend_Validate_Hostname::INVALID_HOSTNAME => 'I don't know your hostname'
    )
);
	
$validator = new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS, false, $hostname);
$validator->setMessages(
    array(
        Zend_Validate_EmailAddress::INVALID => 'Are you sure this is a email address?'
    )
);

Quite complicated, isn’t it ?
Specially when you are using Zend_Form and want to add validators by using addValidator this can become impossible.

So I added a new feature which is available as with Zend Framework 1.10. With it you can set hostname messages from within the email validator… the above code can then be simplified to:

$validator = new Zend_Validate_EmailAddress();
$validator->setMessages(
    array(
        Zend_Validate_Hostname::UNKNOWN_TLD => 'I don't know your TLD',
        Zend_Validate_Hostname::INVALID_HOSTNAME => 'I don't know your hostname'
        Zend_Validate_EmailAddress::INVALID => 'Are you sure this is a email address?'
    )
);

Same can be done within Zend_Form… you can simply set the messages for the hostname validator from the set email validator:

$this->addValidators('emailAddress', false, 'messages' =>
    array(
        Zend_Validate_Hostname::UNKNOWN_TLD => 'I don't know your TLD',
        Zend_Validate_Hostname::INVALID_HOSTNAME => 'I don't know your hostname'
        Zend_Validate_EmailAddress::INVALID => 'Are you sure this is a email address?'
    )
);

I hope you find this new feature usefull.
Have a good work with Zend Framework.

Greetings
Thomas Weidner
I18N Team Leader, Zend Framework

Zend Framework Advisory Board Member
Zend Certified Engineer for Zend Framework

Back to top