PHP - 更清洁,更优雅的方式来验证表单的内容

时间:2011-11-04 16:57:36

标签: php forms coding-style submit

我目前正在处理上传页面,用户在表格中输入值,然后点击提交。我将检查表单是否已提交,如果提交表明它们不是空的。这是我目前的代码

function validPost()
{
    if(isset($_POST["title"]) && //if a post has been submitted
       isset($_POST["artist"]) &&
       isset($_POST["genre"]) &&
       isset($_POST["url"]) &&
       isset($_POST["user"]) ) 
    { 
        if (strlen($_POST['title']) <= 0) {
            echo 'ERROR: Please enter a title. </ br>';
            return false;
        }
        else if (strlen($_POST['artist']) <= 0) {
            echo 'ERROR: Please enter an artist. </ br>';
            return false;
        }
        else if (strlen($_POST['genre']) <= 0) {
            echo 'ERROR: Please select a genre. </ br>';
            return false;
        }
        else if (strlen($_POST['url']) <= 0) {
            echo 'ERROR: Please enter a url. </ br>';
            return false;
        }
        else if (strlen($_POST['user']) <= 0) {
            echo 'ERROR: Please enter a username to submit the song (or make one up). </ br>';
            return false;
        }
        else
            return true;
    }
    else //if no post was submitted
    { 
        return false;
    }
}

有更优雅的方式来检查吗?我计划将来为这些表单提交的内容添加更多检查,我觉得这是一种草率的方式。

谢谢!

2 个答案:

答案 0 :(得分:7)

假设所有字段仅检查非零字符串长度:

$field_checks = array(
//   'fieldname' => 'errormessage'
   'title' => 'Please enter a title',
   'url' => 'Please enter a URL',
   etc...
);

$errors = array();    
foreach ($field_checks as $field => $errmsg) {       
    if (!isset($_POST[$field]) || ($_POST[$field] === '')) {
        $errors[] = $errmsg;
    }
}

if (count($errors) > 0) {
     print_r($errors); // probably want a nicer error display than this
     return false;
}

答案 1 :(得分:-2)

检查jQuery和validate插件