我想重构这段代码,它从表单中获取输入,然后清理输入,然后检查它是空的还是太短。它为标题,内容和标签执行此操作。它存储了一个名为errors的数组中遇到的错误。
我想创建一个函数,如下所示:
function validate_input($args)
除了我不确定我将如何实现它,以及它将如何构建错误列表。
(我知道我可以使用像PEAR QUICKFORM或php-form-builder-class这样的东西,所以请不要提及'哦使用Class xyz')。
$title = filter_input(INPUT_POST, 'thread_title', FILTER_SANITIZE_STRING,
array('flags' => FILTER_FLAG_STRIP_HIGH|FILTER_FLAG_STRIP_LOW ));
$content = filter_input(INPUT_POST, 'thread_content');
$tags = filter_input(INPUT_POST, 'thread_tags');
# title here:
if (is_null($title) || $title == "") # is_null on its own returns false for some reason
{
$errors['title'] = "Title is required.";
}
elseif ($title === false)
{
$errors['title'] = "Title is invalid.";
}
elseif (strlen($title) < 15)
{
$errors['title'] = "Title is too short, minimum is 15 characters (40 chars max).";
}
elseif (strlen($title) > 80 )
{
$errors['title'] = "Title is too long, maximum is 80 characters.";
}
# content starts here:
if (is_null($content) || $content == "")
{
$errors['content'] = "Content is required.";
}
elseif ($content === false)
{
$errors['content'] = "Content is invalid.";
}
elseif (strlen($content) < 40)
{
$errors['content'] = "Content is too short, minimum is 40 characters."; # TODO: change all min char amounts
}
elseif (strlen($content) > 800)
{
$errors['content'] = "Content is too long, maximum is 800 characters.";
}
# tags go here:
if (is_null($tags) || $tags == "")
{
$errors['tags'] = "Tags are required.";
}
elseif ($title === false)
{
$errors['tags'] = "Content is invalid.";
}
elseif (strlen($tags) < 3)
{
$errors['tags'] = "Atleast one tag is required, 3 characters long.";
}
var_dump($errors);
答案 0 :(得分:0)
如果正确理解你的问题并且你只想验证和消毒那三个变量,那应该非常简单。
function validateAndSanitizeInput(Array $args, Array &$errors) {
//validation goes in here
return $args;
}
在这种情况下,errors数组通过引用传递,这样您就可以在调用函数后从中获取错误消息。
$errors = array();
$values = validateAndSanitizeInput($_POST, $errors);
//print $errors if not empty etc.
顺便说一句,您可以将“is_null($ content)|| $ content ==”“”替换为“empty($ content)”