【发布时间】:2010-10-18 22:10:26
【问题描述】:
我已经成为一名 PHP 开发人员已经有一段时间了,但直到今天我还没有找到一种简单的处理方法(也就是规范化、清理、验证、填充和显示表单以及相应的字段错误)。
我知道现在大多数 PHP 框架使这项工作变得更容易,但不知何故,我不想将我所有的代码移植到其中一个框架中,而且我不太明白表单验证是如何在 Django 中实现的例如(我知道,它是 Python,但我真的很喜欢他们的方法),所以我认为最好的方式是在这里发布我处理简单表单的方式,也许你们可以为我指明最佳方向。
<?php
// sample controller
class _sample extends framework
{
// sample action
function contact()
{
if ($this->Is->Post() === true)
{
$errors = array();
if ($this->Is->Set($_POST['name']) === false)
{
$errors['name'] = 'Please fill in your name.';
}
if (($this->Is->Email($_POST['email']) === false) || ($this->Is->Set($_POST['email']) === false))
{
$errors['email'] = 'Please fill in your email address.';
}
if (($this->Is->Phone($_POST['contact']) === false) && ($this->Is->Mobile($_POST['contact']) === false))
{
$errors['contact'] = 'Please fill in your phone (or cell phone) number.';
}
if ($this->Is->Set($_POST['message']) === false)
{
$errors['message'] = 'Please type a message';
}
// no errors, it's valid!
if (empty($errors) === true)
{
// do stuff and redirect to "success" / "thank you" page
}
// load the form view, and let it display the errors
// automatically prefill fields with $_POST values
else
{
$this->View('contact_form', $errors);
}
}
// load the form view for the first time
else
{
$this->View('contact_form');
}
}
}
?>
如您所见,这应该是一个简单的联系表单,但它需要我的生命来验证它,我一直在研究一些设计模式(观察者,工厂),但我不相信如果和我应该以什么方式实现它们。
【问题讨论】:
-
如果你觉得有时间,你可以看看Django是怎么做的!
标签: php validation forms