I'm seeking some examples of how people implement validation logic in the Zend Framework.
My ideal implementation would keep the validation outside the controller and allow validating "Confirm password" fields and file uploads.
I'm seeking some examples of how people implement validation logic in the Zend Framework.
My ideal implementation would keep the validation outside the controller and allow validating "Confirm password" fields and file uploads.
你在使用Zend_Form
你的表格吗?我倾向于在表单中为每个Zend_Form_Element
. 我就是这样做的:
class Form_Login extends Zend_Form
{
public function init() {
$this->setMethod('post');
$validator = new Zend_Validate_Regex('([A-Za-z0-9]+)');
$validator->setMessage(
'Your username can only contain letters, numbers and underscores (_).');
$username = new Zend_Form_Element_Text('username');
$username->setLabel('Your Username');
$username->setDescription('The username you use to login');
$username->setAllowEmpty(false);
$username->setRequired(true);
$username->addValidator($validator);
$submit = new Zend_Form_Submit('login');
$submit->setLabel('Login');
$this->addElements(array($username, $submit));
}
}
(自定义错误消息)
然后在你的控制器中:
// $form is an instance of the extended Zend_Form
if (!$form->isValid()) {
$validator->getMessages()
// flashMessenger helpers or just simple view appends
}
我理想的实现方式是将验证保持在控制器之外,并允许验证“确认密码”字段和文件上传。
我在参考指南中看到了确认密码验证器的提及(但现在找不到它们,典型的),但在 Google 上应该很容易找到。
文件上传肯定需要您编写自定义验证器。
也许你应该看看。Matthew Weier O'Phinney(Zend Fraework 核心开发人员之一)展示了一种需要习惯的方法 - 但值得一看。
是的,这是进行数据验证的推荐方法。谢谢!我想看到更多的例子。
谈到 HTML,我有点控制狂,所以我尽量远离 Zend_Form。我知道它可以进行大量定制,但我记得在某些时候遇到了障碍,所以我决定坚持使用纯 html 表单。
特别是对于“确认密码”类型的验证,请查看 Zym 框架(Zend 框架扩展)。它有一个用于这个确切目的的内置验证器。试试Zym_Validate_Confirm类。