重构php中的表单代码
我从表单中获取三个值(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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).