我已经看到在SocialEngine代码中的表单元素上成功使用了验证器,因此,当用户添加无效输入时,将显示错误消息。例如,通过在添加新表单元素时指定“ NonEmpty”验证器并指定要为此验证器显示的消息,为该元素提交空值的用户将看到一条错误消息。我正在使用以下代码创建表单,然后在控制器中处理表单。一切似乎都很好,但我不知道为什么它不起作用。无论输入什么,都不会显示验证器消息。
class Advancedsms_Form_ChangePassword extends Engine_Form {
public function init() {
parent::init();
$tabIndex = 10;
$this->setTitle(Zend_Registry::get('Zend_Translate')->_('Change Password'))
->setDescription(Zend_Registry::get('Zend_Translate')->_('Enter your new password'))
-> setAttrib('id', 'change_password')
-> setAttrib('enctype', 'multipart/form-data')
->setAction(Zend_Controller_Front::getInstance()->getRouter()->assemble([]));
$this->addElement('Password', 'password', [
'label'=> Zend_Registry::get('Zend_Translate')->_('New Password'),
'description' => Zend_Registry::get('Zend_Translate')->_('Enter Your New Password'),
'required' => true,
'validators' => [
['NotEmpty', true],
['StringLength', true,[8,32]],
['Regex', true, ['/^[a-zA-Z0-9_$/i']],
],
'tabindex' => $tabIndex++,
]);
$this->password->getValidator('NotEmpty')->setMessage(Zend_Registry::get('Zend_Translate')->_('Phone number cannot be empty'),'isEmpty');
$this->password->getValidator('StringLength')->setMessage(Zend_Registry::get('Zend_Translate')->_('Phone length is not correct'));
$this->addElement('Password', 'password_confirm', [
'label' => Zend_Registry::get('Zend_Translate')->_('Confirm Your New Password'),
'description' => Zend_Registry::get('Zend_Translate')->_('Confirm Your New Password'),
'required' => true,
'validators' => [
['NotEmpty', true],
['StringLength', true, [8, 32]],
['Regex',true, ['/^[a-ZA-Z0-9_$/i']],
],
'tabindex' => $tabIndex++,
]);
$this->addElement('submit', 'submit', [
'label'=> Zend_Registry::get('Zend_Translate')->_('Submit'),
'required' => true,
'tabindex' => $tabIndex++,
]
);
}
}
操作:
public function changepasswordAction() {
$passwordForm = new Advancedsms_Form_ChangePassword();
$this->view->form = $passwordForm;
//Access Zend_Session_Namespace
$this->session = new Zend_Session_Namespace('RecoverySession');
//If it is NOT post, the user has to provide recovery code and phone number
if (!$this->getRequest()->isPost()) {
$phone = filter_input(INPUT_GET, 'phone', FILTER_SANITIZE_URL);
$recovery = filter_input(INPUT_GET, 'recovery', FILTER_SANITIZE_URL);
$this->session->phone = $phone;
$this->session->recoveryCode = $recovery;
}
if ($this->getRequest()->isPost()) {
//Check passwords validity
$params = $this->getRequest()->getPost();
$password = $params['password'];
$passwordConfirm = $params['password_confirm'];
if($password == $passwordConfirm) {
$this->view->form->addNotice('Passwords match');
}
else {
$this->view->form->addError('Passwords do not match');
}
}