Making zend EmailAddress form validator return only one custom error message
I'm creating an email form element like so (inside a Zend Form):
//create e-mail element
$email = $this->createElement('text', 'username')
->setLabel('E-mail:')
开发者_运维问答 ->setRequired(true)
->addFilters(array('StringTrim', 'StringToLower'))
->addValidator('EmailAddress', false, array(
'messages' => array(
Zend_Validate_EmailAddress::INVALID => 'Dit e-mail adres is ongeldig.',
)
));
//add element
$this->addElement($email);
Now, when an invalid e-mail is entered quite a lot of messages appear:
'#' is no valid hostname for email address '@#$@#'
'#' does not match the expected structure for a DNS hostname
'#' does not appear to be a valid local network name
'@#$' can not be matched against dot-atom format
'@#$' can not be matched against quoted-string format
'@#$' is no valid local part for email address '@#$@#'
I wonder, is it possible to make it only emit the error message provided by me, such as 'Please enter a valid e-mail address.'?
The easiest way is to use addErrorMessage()
to set a single custom message for all errors.
In your example you can add it to your code and call it fluently, or add the line
$email->addErrorMessage('Dit e-mail adres is ongeldig.');
You should also change the second parameter to addValidator as below, so that once validation has failed other conditions aren't checked.
->addValidator('EmailAddress', true)
It is explained in the Reference Guide but not very well. The name addErrorMessage
doesn't imply that it will override the default messages, but there you are.
You could use either :
$email->addErrorMessage('Dit e-mail adres is ongeldig.');
$email->addValidator('EmailAddress', true);
Or you can use :
$email_validate = new Zend_Validate_EmailAddress();
$email_validate->setMessage("Your custom message");
$email->addValidator($email_validate ,TRUE);
精彩评论