問題描述
我正在構建一個 ZendFramework 應用程序,它作為一個要求輸入電子郵件地址和密碼的登錄表單 - 在嘗試登錄數據庫之前驗證電子郵件地址似乎是有意義的,因為無效的電子郵件永遠不會導致有效命中.Zend_Validate_EmailAddress 似乎是正確的方法,但我遇到了一個問題,它會產生多個錯誤(底部的問題,代碼之后).
I am building a ZendFramework application which as a login form asking for an email address and password - it seemed to make sense to validate the email address before hitting the database with the login attempt, as an invalid email would never lead to a valid hit. Zend_Validate_EmailAddress seemed like the right way to go, but I am having an issue with it generating multiple errors (question at the bottom, after the code).
我的表單目前有以下內容
My form currently has the following
//WPMail_Form_Login::init()
$email = $this->addElement('text', 'email', array(
'label'=>'Email',
'required'=>true,
'filters'=>array('stringtrim'),
'validators'=>array(array('emailaddress', true, array(
'messages'=>array(
'emailAddressInvalidHostname'=>'Your email address is invalid',
'emailAddressInvalidFormat'=>'Your email address is invalid',
'...'=>'(repeat for all message templates)'
)
))),
));
在控制器中,我直接將表單傳遞到視圖中:
In the controller I directly pass the form into the view:
// WPMail_AuthController::loginAction()
$this->view->form = $form;
在視圖中,它是直接回顯的:
And in the view, it's directly echo'd:
// views/scripts/auth/login.phtml
<?php echo $this->form ?>
目前的結果是這樣的:
- Your email address is invalid
- 'asda!!!' does not match the expected structure for a DNS hostname
- 'asda!!!' does not appear to be a valid local network name
我想知道的是:是否可以將 Zend_
Validate_
EmailAddress 配置為只產生一個電子郵件無效錯誤?我所說的配置"是指不擴展類并用我自己的邏輯覆蓋邏輯.
What I want want to know is: Is it possible to configure Zend_
Validate_
EmailAddress in such a way that it only produces a single email-invalid error? By 'configure' I mean, without extending the class and overriding the logic with my own.
TIA.
推薦答案
Zend Form Element 有多種方法可用于自定義消息.從文檔中并不是很清楚,但是 addErrorMessage() 會在驗證失敗時設置一條自定義錯誤消息.
Zend Form Element has various methods you can use to customise messages . It's not terribly clear from the docs but addErrorMessage() sets a single custom error message on failed validation.
因此,您的示例如下所示:
Your example would therefore look like:
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email')
->setRequired(true)
->addFilter('stringtrim')
->addValidator('emailAddress', true)
->addErrorMessage('Your email address is invalid');
$this->addElement($email);
參見 http:///framework.zend.com/manual/en/zend.form.elements.html#zend.form.elements.validators.errors
這篇關于在 Zend_Form 中,如何避免 Zend_Validate_Email 產生多個錯誤?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!