zend 表单电子邮件验证

发布于 2024-10-08 10:19:14 字数 1431 浏览 5 评论 0原文

我有以下代码来生成用户电子邮件地址的输入字段,

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress')
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                                                        array(
                                                                'adapter'=>Zend_Registry::get('user_db'),
                                                                'field'=>'email',
                                                                'table'=>'tbl_user'
                                                                )))
    ->setRequired(true)
    ->setDecorators(array(
                            array('Label', array('escape'=>false, 'placement'=>'append')),
                            array('ViewHelper'),
                            array('Errors'),
                            array('Description',array('escape'=>false,'tag'=>'div')),
                            array('HtmlTag', array('tag' => 'div')),
                        ));
$this->addElement($email);

现在的问题是如果用户输入无效的电子邮件主机名,则会生成 3 个错误。假设用户输入“admin@l”作为电子邮件地址,错误将是
*“l”不是电子邮件地址“admin@l”的有效主机名
*“l”与 DNS 主机名的预期结构不匹配
*“l”似乎是本地网络名称,但不允许本地网络名称,

我只想它只给出一个自定义错误,而不是所有这些错误。如果我通过 addErrorMessage 方法设置错误消息“无效的电子邮件地址”,它将再次针对 db_validation 生成相同的消息。

I have the following code to generate an input field for user's email address

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress')
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                                                        array(
                                                                'adapter'=>Zend_Registry::get('user_db'),
                                                                'field'=>'email',
                                                                'table'=>'tbl_user'
                                                                )))
    ->setRequired(true)
    ->setDecorators(array(
                            array('Label', array('escape'=>false, 'placement'=>'append')),
                            array('ViewHelper'),
                            array('Errors'),
                            array('Description',array('escape'=>false,'tag'=>'div')),
                            array('HtmlTag', array('tag' => 'div')),
                        ));
$this->addElement($email);

now the problem is if user enter invalid hostname for email, it generate 3 errors. lets say user enter 'admin@l' as email address, and the errors will be
* 'l' is no valid hostname for email address 'admin@l'
* 'l' does not match the expected structure for a DNS hostname
* 'l' appears to be a local network name but local network names are not allowed

I just want it to give only one custom error instead of all these. If I set error message "Invalid Email Address" by addErrorMessage method, it will again generate the same message against the db_validation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

半衬遮猫 2024-10-15 10:19:14

嗯,这是一个迟到的答案,但我认为总是有用的。

只需添加 true 作为

Zend 文档中 addValidator() 的第二个参数 (http://framework.zend.com/apidoc/1.8/):

addValidator(第 67 行)

将验证器添加到链的末尾

如果 $breakChainOnFailure 为 true,那么如果验证器失败,则下一个
链上的验证器,如果存在,则不会被执行。

返回:提供流畅的界面

访问:公开

这里签名:

Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])

Zend_Validate_Interface $validator
boolean $breakChainOnFailure

所以代码是:

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress',  TRUE  ) // added true here
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                array(
                        'adapter'=>Zend_Registry::get('user_db'),
                        'field'=>'email',
                        'table'=>'tbl_user'
                        ), TRUE )
            );

Well, it's a late answer but I think is always useful.

Simply add true as second param of addValidator()

From Zend docs (http://framework.zend.com/apidoc/1.8/):

addValidator (line 67)

Adds a validator to the end of the chain

If $breakChainOnFailure is true, then if the validator fails, the next
validator in the chain, if one exists, will not be executed.

return: Provides a fluent interface

access: public

Here the signature:

Zend_Validate addValidator (Zend_Validate_Interface $validator, [boolean $breakChainOnFailure = false])

Zend_Validate_Interface $validator
boolean $breakChainOnFailure

So the code is:

$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email:')
    ->addFilters(array('StringTrim', 'StripTags'))
    ->addValidator('EmailAddress',  TRUE  ) // added true here
    ->addValidator(new Zend_Validate_Db_NoRecordExists(
                array(
                        'adapter'=>Zend_Registry::get('user_db'),
                        'field'=>'email',
                        'table'=>'tbl_user'
                        ), TRUE )
            );
£噩梦荏苒 2024-10-15 10:19:14

您必须创建 Zend_Validate_EmailAddress 类的实例并调用 setMessages 方法,然后重写您喜欢的消息,以删除您提到的消息,它会是这样的:

$emailValidator->setMessages(array(
    Zend_Validate_EmailAddress::INVALID_FORMAT => "Your error message",
    Zend_Validate_Hostname::INVALID_HOSTNAME => "Your error message",
    Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED => "Your error message"
));

我希望这可以帮助某人:-)

You have to create an instance of the Zend_Validate_EmailAddress class and call the setMessages method and then override the messages that you like, to remove the ones that you mention it would be something like this:

$emailValidator->setMessages(array(
    Zend_Validate_EmailAddress::INVALID_FORMAT => "Your error message",
    Zend_Validate_Hostname::INVALID_HOSTNAME => "Your error message",
    Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED => "Your error message"
));

I hope this help somebody :-)

晚风撩人 2024-10-15 10:19:14
$email->addErrorMessage("Please Enter Valid Email Address");

您可以使用自定义验证器。在项目根目录的 library 文件夹

class Validate_Email extends Zend_Validate_Abstract
{

    const INVALID = 'Email is required';
    protected $_messageTemplates = array(
    self::INVALID => "Invalid Email Address",
    self::ALREADYUSED => "Email is already registered"
    );

     public function isValid($value)
     {
          if(preg_match($email_regex, trim($value))){
            $dataModel = new Application_Model_Data(); //check if the email exists
            if(!$dataModel->email_exists($value)){
                return true;
            }
            else{
                $this->_error(self::ALREADYUSED);
                return false;
            }
          }
          else
          {
            $this->_error(self::INVALID);
            return false;
          }
     }
}

form.php

    $mailValidator = new Validate_Email();
    $email->addValidator($mailValidator, true);

Validate 文件夹中创建一个文件 Email.php不知道它是否有效,但对我来说,它在电话情况下有效 由 http://softwareobjects.net/technology/ 提供其他/zend-framework-1-10-7-电话-验证器/

$email->addErrorMessage("Please Enter Valid Email Address");

you can use custom validator. create a file Email.php inside folder Validate in your library folder at the root of project

class Validate_Email extends Zend_Validate_Abstract
{

    const INVALID = 'Email is required';
    protected $_messageTemplates = array(
    self::INVALID => "Invalid Email Address",
    self::ALREADYUSED => "Email is already registered"
    );

     public function isValid($value)
     {
          if(preg_match($email_regex, trim($value))){
            $dataModel = new Application_Model_Data(); //check if the email exists
            if(!$dataModel->email_exists($value)){
                return true;
            }
            else{
                $this->_error(self::ALREADYUSED);
                return false;
            }
          }
          else
          {
            $this->_error(self::INVALID);
            return false;
          }
     }
}

and in you form.php file

    $mailValidator = new Validate_Email();
    $email->addValidator($mailValidator, true);

Don't know if it works or not but for me it worked in case of telephone. Courtesy of http://softwareobjects.net/technology/other/zend-framework-1-10-7-telephone-validator/

紙鸢 2024-10-15 10:19:14

它似乎缺少很多行......

可能应该使用这个:
$mailValidator = new Zend_Validate_EmailAddress();

您还可以执行一些其他验证,请参见此处: http://framework.zend .com/manual/en/zend.validate.set.html

It seems to be missing quite a few lines...

probably should use this:
$mailValidator = new Zend_Validate_EmailAddress();

you can also do some other validations see here: http://framework.zend.com/manual/en/zend.validate.set.html

攀登最高峰 2024-10-15 10:19:14

使用自定义验证器是我发现避免此问题的唯一方法。

如果您想要的是:

  • 如果电子邮件地址格式错误,则只有一条错误消息
  • 如果格式正确,则验证电子邮件地址是否已在数据库中

那么我建议您这样做像这样的东西:

$where = array('users', 'email', array('field' => 'user_id',
                                       'value' => $this->getAttrib('user_id')));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail:')
      ->setRequired(true)
      ->setAttrib('required name', 'email') // html5
      ->setAttrib('maxlength', '50')
      ->addFilter('StripTags')
      ->addFilter('StringTrim')
      ->addFilter('StringToLower')
      ->addValidator('email', true)
      ->addValidator('stringLength', true, array(1, 50))
      ->addValidator('db_NoRecordExists', true, $where)
      ->addDecorators($this->_elementDecorators);
$this->addElement($email);

$this->getAttrib('user_id') 代表当前用户的 ID

这里有三个验证器,它们的第二个参数$breakOnFailure都设置为false,所以如果一个验证器失败,其他验证器将不会被调用。

第一个验证器是email,这是我自己的自定义验证器:

class My_Validate_Email extends Zend_Validate_EmailAddress
{
    public function getMessages()
    {
        return array('invalidEmail' => 'Your email address is not valid.');
    }
}

您可以在您的库中添加此验证器,例如在 /application/library/My/Validate 中,然后添加
$this->addElementPrefixPath('My_Validate', 'My/Validate', 'validator');
进入你的表格。当然,您需要将“My”替换为您的图书馆名称。

现在,如果电子邮件格式错误,它将始终显示“您的电子邮件地址无效。”。如果您的电子邮件太长并且不适合您的数据库字段(例如 VARCHAR(100)),它将显示您的 stringLength 验证器错误,在最后一种情况下,如果数据库中已存在条目,则仅此将显示错误。

当然,您可以在自定义验证器中添加更多方法并重载 setMessages,以便您可以显示自己的消息,无论您正在处理什么表单。

希望它可以帮助别人!

Using a custom validator is the only way I found to avoid this problem.

If what you want is:

  • Having only one error message if the email address is in a wrong format
  • If the format is good, then validate if the email address is already in the database

Then I suggest you to do something like this:

$where = array('users', 'email', array('field' => 'user_id',
                                       'value' => $this->getAttrib('user_id')));
$email = new Zend_Form_Element_Text('email');
$email->setLabel('E-mail:')
      ->setRequired(true)
      ->setAttrib('required name', 'email') // html5
      ->setAttrib('maxlength', '50')
      ->addFilter('StripTags')
      ->addFilter('StringTrim')
      ->addFilter('StringToLower')
      ->addValidator('email', true)
      ->addValidator('stringLength', true, array(1, 50))
      ->addValidator('db_NoRecordExists', true, $where)
      ->addDecorators($this->_elementDecorators);
$this->addElement($email);

$this->getAttrib('user_id') represents the current user's id.

There are three validators here, all of them have their second parameter $breakOnFailureset to false, so if a validator fails, the other ones won't be called.

The first validator is email, which is my own custom validator:

class My_Validate_Email extends Zend_Validate_EmailAddress
{
    public function getMessages()
    {
        return array('invalidEmail' => 'Your email address is not valid.');
    }
}

You can add this validator in your library, in /application/library/My/Validate for example, and then add
$this->addElementPrefixPath('My_Validate', 'My/Validate', 'validator');
into your form. Of course, you need to replace "My" by the name of your library.

Now if an email is in the wrong format, it will always display 'Your email address is not valid.'. If your email is too long and doesn't fit into your database field (VARCHAR(100) for example), it's going to show your stringLength validator errors, and in the last case, if an entry already exists in the database, only this error will be shown.

Of course you can add more methods into your custom validator and overload setMessages, so that you can display your own messages whatever the form you are working on.

Hope it can help someone!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文