重构php中的表单代码

发布于 2024-10-16 17:04:04 字数 980 浏览 5 评论 0原文

我从表单中获取三个值(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

如果错误数组为空,我将清理数据并提交它到数据库。如何使这段代码变得更清晰、重构?

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

I get three values from a form (thread_title, thread_content and thread_tags):

This is the code to check their lengths:

$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.';
}

I repeat this in the reply.php file:

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

.etc

If the errors array is empty I then clean the data and submit it to the database. How can this code be made cleaner, refactored?

I know I can use something like PEAR QUICK_FORM (2.0?), however that is still in alpha and the error messages appear as a JS popup in that and not next to the required field.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉梦枕江山 2024-10-23 17:04:04

github 是许多优秀代码的来源。我快速搜索了 表单验证。例如:

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

github is a source of lot of really good code. I did a quick search for form validation. For example:

Furthermore I believe if you want to refactor your code, you should practice TDD(unit testing).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文