Reputation: 6155
I am wondering how to change the email error message returned from a form:
The error in the image is pretty ugly.
This is my form:
$this->add(
[
'name' => 'email',
'type' => 'email',
'options' => [
'label' => 'E-Mail',
'instructions' => 'Your email address'
],
'attributes' => [
'class' => 'form-element',
'required' => 'required',
]
]
);
Would be nice for the message to state: "That email is already registered" or "Email [email protected] is already in use"
How do you do this?
Upvotes: 0
Views: 40
Reputation: 1890
This is my way of validating emails for registration. It will strip all tags, trim the email, see if the input field is empty, if the email is at least 5 chars long and if the email contains only valid chars.
public function getInputFilterSpecification()
{
return [
[
"name"=>"email",
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
"validators" => [
[
'name' => 'EmailAddress',
'options' => [
'encoding' => 'UTF-8',
'messages' => ['emailAddressInvalidFormat' => "Email address doesn't appear to be valid."],
],
],
[
'name' => 'StringLength',
'options' => [
'encoding' => 'UTF-8',
'min' => 5,
],
],
['name' => 'NotEmpty'],
],
],
];
}
If you simply want to check for existing email inside your database, I would suggest you to do this in your controller, when the form has been submitted and return error/success message depending if the email is there or not. For this you can try this code.
$email = '[email protected]';
$emailQuery = $db->findEmail('email = ?', $email);
$validator = new Zend\Validator\Db\RecordExists(
[
'table' => 'users',
'field' => 'email',
'exclude' => $emailQuery
]
);
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
Upvotes: 1