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;
}
Check into jQuery and the validate plugin