在php中重构表单代码

时间:2011-02-06 23:14:01

标签: php refactoring

我从表单中获取三个值(thread_title,thread_content和thread_tags):

这是检查其长度的代码:

$errors = array();

$thread_title = filter_input(INPUT_POST, 'thread_title');
$thread_content = filter_input(INPUT_POST, 'thread_content');
$thread_tags = filter_input(INPUT_POST, 'thread_tags');


if (strlen($thread_title) < 20 )
{
    $errors['thread_title'] = 'Title is too short, minimum is 20 characters.';    
}

if (strlen($thread_content) < 30 )
{
    $errors['thread_content'] = 'Content is too short, minimum is 30 characters.';
}

if (strlen($thread_tags) < 3)
{
    $errors['thread_tags'] = 'Tags must be atleast 3 characters.';
}

我在reply.php文件中重复这个:

if (strlen($reply_content) < 20)
{
    $errors['reply_content'] = 'Reply must be atleast 20 characters.';
}

.etc

如果errors数组为空,则我清理数据并将其提交给数据库。如何使这些代码变得更干净,重构?

我知道我可以使用像PEAR QUICK_FORM(2.0?)这样的东西,但是它仍然是alpha版本,错误消息显示为JS弹出窗口,而不是必填字段旁边。

1 个答案:

答案 0 :(得分:0)

github是许多非常好的代码的来源。我快速搜索了form validation。例如:

此外,我相信如果你想重构你的代码,你应该练习TDD(单元测试)。