如何使用表单在 ZF2 中获得更好的电子邮件错误

How to get a better email error in ZF2 using Forms

我想知道如何更改从表单返回的电子邮件错误消息:

图片中的错误非常难看。

这是我的表格:

    $this->add(
        [
            'name'       => 'email',
            'type'       => 'email',
            'options'    => [
                'label' => 'E-Mail',
                'instructions' => 'Your email address'

            ],
            'attributes' => [
                'class' => 'form-element',
                'required' => 'required',
            ]
        ]
    );

最好在消息中说明:"That email is already registered" 或 "Email me@example.com is already in use"

你是怎么做到的?

这是我验证注册电子邮件的方式。它将去除所有标签,trim 电子邮件,查看输入字段是否为空,电子邮件是否至少 5 个字符长以及电子邮件是否仅包含有效字符。

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'],
            ],
        ],
     ];
}

如果您只是想检查数据库中现有的电子邮件,我建议您在提交表单和 return error/success 消息时在控制器中执行此操作,具体取决于电子邮件是否存在。为此,您可以尝试此代码。

$email = 'me@example.com';
$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";
    }
}