Restricting A User’s Email To A Specific Domain With Custom Zend Validator

At work, some of our online forms need to make sure that user’s use a specific email address. Since I write most of my forms with Zend, I was hoping there was already a validator for that, nope. Oh well, it wasn’t that hard to write one.

The following class will make sure that a given email address is from a specific domain. (This won’t verify it’s an email, though I could of just extended Zend_Validate_EmailAddress)


'Invalid domain used.',
self::NO_DOMAIN => 'No email domain provided.'
);

public function __construct($allowedDomain, $options = array()){
$this->_allowedDomain = $allowedDomain;
}

public function isValid($email)
{
$this->_setValue($email);

$domain = explode('@', $email);

// If no domain.
if(count($domain) == 1){
$this->_error(self::NO_DOMAIN);
return false;
}
// Wrong domain used.
if($domain[1] != $this->_allowedDomain){
$this->_error(self::BAD_DOMAIN);
return false;
}

return true;
}
}

To implement it on a form element:


$this->addElement('text', 'email', array(
'label' => 'Email:',
'description' => '(Please use your @my.domain.com account.)',
'validators' => array(
array('EmailDomain', true, array('my.domain.com')),
array('EmailAddress', false, array('messages' => 'Please use your my.domain.com email address.'))
)
));

One thought on “Restricting A User’s Email To A Specific Domain With Custom Zend Validator”

Leave a Reply

Your email address will not be published. Required fields are marked *