[英]PHP - Cleaner, More Elegant Way to Validate Content of Forms
I am currently working on a Upload page, where users enter in values to forms then click submit. 我目前正在上载页面,用户在其中输入表单值,然后单击提交。 I am going to check to see if the forms have been submitted, and if submitted that they weren't empty. 我将检查表单是否已提交,以及是否已提交表单。 Here is my current code 这是我当前的代码
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;
}
}
Is there a more elegant way to check this? 有没有更优雅的方法来检查这一点? I plan on adding more checks in the future to the content submitted by these forms and I feel like this is a sloppy way to do it. 我计划将来在这些表单提交的内容中添加更多支票,我觉得这是一种草率的做法。
Thanks! 谢谢!
Assuming that all of the fields will be check for non-zero string lengths only: 假设将仅检查所有字段的非零字符串长度:
$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;
}
签入jQuery和validate插件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.