2011-02-11 62 views
0

我想重构这段代码,它从一个表单输入,然后清理输入,然后检查它是空的还是太短。它为标题,内容和标签执行此操作。它存储一个名为errors的数组中遇到的错误。重构php过滤器/验证

我想要的功能,这样的事情:

function validate_input($args) 

除了我不确定为我如何去实现它,以及它如何会建立一个错误列表。

(我知道我可以使用PEAR QUICKFORM或php-form-b​​uilder-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

应该很简单,如果正确地理解你的问题,并且你想验证和消毒只有这三个变量。

function validateAndSanitizeInput(Array $args, Array &$errors) { 
//validation goes in here 
return $args; 
} 

在这种情况下,错误数组通过引用传递,所以你就可以从中获得错误信息的函数被调用后。

$errors = array(); 
$values = validateAndSanitizeInput($_POST, $errors); 
//print $errors if not empty etc. 

通过,你可以替换的方式 “is_null($内容)|| $内容== ”“,” 与 “空($内容)”