I would like to cycle through all the elements in a submitted form, assign each element its own variable, and then check if they are required. IF they are required, they will be checked if they are empty. So far, my form looks like this:
<form id="newitem" action="addnew.php" method="POST">
<label for="title">Title: </label>
<input type="text" name="title" id="title" required="required" /><br />
<label for="description">Description: </label>
<textarea name="description" id="website" cols="40" rows="5" ></textarea><br />
<input type="hidden" name="formsubmit" value="true" /><!-- Option to know we've sumbited the form -->
<input type="submit" value="Submit" id="submit" />
</form>
I then have it validated using this:
if (isset($_POST['formsubmit'])) {
// form has been submitted
$errors = Array();
foreach($_POST as $key => $value) {
$$key = $value;
if (!$value) {
array_push($errors, 'Please enter a value for ' . $key);
}
}
if (count($errors) == 0) {
echo 'Form validated';
} else {
showErrors($errors);
}
}
This currently checks if the elements have a value. However, I would like it to check if that field is required, using the HTML required="required".
Also, although I feel I do understand how this works, I’m not sure I do. I think $$key = $value basically means create a variable with the value of $key and give it the value of $value. So, $key is the name of the element, whilst $value is its value. However, I really don’t get the foreach($_POST as $key => $value) {. I know it cycles though all the $_POST‘s, but don’t really know any more than that.
Thanks for any help!
If think you are looking for something like
Foreach loops over an associative array and gives you the key and value of every ‘element’ in the array. In this case it will give you the name of a field in $key and the value of a field in $value.
See http://php.net/manual/en/control-structures.foreach.php for more info.
However, if a field was not submitted at all (i.e. not send from the client to the back-end), the $_FORM would not contain that field at all. Thus, to check if some required fields are filled, you would need to have that list on the serverside as well..! The code would then be something like: