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($repl开发者_如何学运维y_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.
github is a source of lot of really good code. I did a quick search for form validation. For example:
- https://github.com/bretticus/PHP-5.3-Form-Validator looks okay?
Furthermore I believe if you want to refactor your code, you should practice TDD(unit testing).
精彩评论