[英]Custom Validator Issue in Zend Framework
我有一個名為LoginForm的表單,該表單擴展了RecipeForm,而后者又擴展了Zend_Form。 RecipeFrom僅返回我的裝飾器。
提交表單后,出現以下錯誤,“消息:方法addValidator不存在”。
class Recipe_Form_LoginForm extends Recipe_Form_RecipeForm {
public function init()
{
parent::init();
$this->setName('loginform')
->setAction('/login');
// Add Email Element
$email = $this->addElement('text', 'email', array(
'label' => 'Email Addresses',
'required'=> true,
'size'=>12,
'filters'=>array('StringTrim'),
'decorators' => $this->getElementDecorator('email'),
));
$email->addValidator(new Recipe_Validate_EmailAddress(), true, array(
'messages' => array(
Recipe_Validate_EmailAddress::INVALID =>
'Please enter email in correct format',
Recipe_Validate_EmailAddress::EMAILISEMPTY =>
'Please enter email address'
)));
}
class Recipe_Validate_EmailAddress extends Zend_Validate_Abstract
{
const INVALID = 'notvalid';
const EMAILISEMPTY = 'isempty';
protected $_messageTemplates = array(
self::INVALID => "Email is in invalid format",
self::EMAILISEMPTY => "You have to fill email field"
);
public function isValid($value){
$response = parent::isValid($value);
if(!$response){
$this->_message = array(self::INVALID => "Please enter a valid email address");
}
return $response;
}
}
?>
當您從Zend_Form對象中調用$this->addElement()
,它將返回表單對象本身,而不是您剛創建的元素。
您可以進行以下更改之一:
$this->addElement('text', 'email', ...);
$email = $this->getElement('email');
$email->addValidator(...);
// or
$email = new Zend_Form_Element_Text('email');
$email->addValidator(...)
->setLabel(...)
->setRequired(...);
$this->addElement($email);
要設置錯誤消息,我認為您應該這樣做而不是設置$ this-> _ message。
$this->_error(self::INVALID);
由於看起來您的班級只是擴展Zend的電子郵件驗證程序以覆蓋消息,因此您可以像這樣覆蓋Zend的消息,而無需擴展類。 這是從我的一個項目的驗證器中獲取的,因此請忽略多余的內容,而只需注意EmailAddress驗證器的消息。
$this->addElement('text', 'email', array(
'label' => 'Email Address:',
'required' => false,
'filters' => array('StringTrim', 'StringToLower'),
'validators' => array(
array('EmailAddress', true, array(
'messages' => array(
Zend_Validate_EmailAddress::INVALID_FORMAT =>
"'%value%' is not a valid email address. Example: you@yourdomain.com",
Zend_Validate_EmailAddress::INVALID_HOSTNAME =>
"'%hostname%' is not a valid hostname for email address '%value%'"
)
)),
array('Db_RecordExists', true, array(
'table' => 'accounts', 'field' => 'email',
'messages' => array(
Zend_Validate_Db_RecordExists::ERROR_NO_RECORD_FOUND =>
"No account with that email address was found"
)
))
),
'decorators' => $this->elementDecorators
));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.