2011-02-11 63 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($內容)|| $內容== 」「,」 與 「空($內容)」