Validation form Enforcing Required Fields

Aug 22, 2009 Author: Developer

The most basic type of form validation is to enforce that a particular field must contain a value. In the case of a text input that is submitted with no value entered, the element in $_POST is still created, but it contains an empty value. Therefore, you cannot use isset to check whether a value was entered; you must check the actual value of the element, either by comparing it to an empty string or by using the following, more compact syntax with the Boolean NOT operator:

if (!$_POST["fieldname"]) { ... }

Because each field on the form creates an element in $_POST, if every field requires a value to be entered, you could use a simple loop to check that there are no empty values in the array:

foreach($_POST as $field => $value) {
if (!$value) {
$err .= "$field is a required field
";
}
}
if ($err) {



echo $err;
echo "Press the back button to fix these errors";
}
else {
// Continue with script
}

Rather than exit as soon as an empty field is found, this script builds up an error string, $err. After the validation is done, the contents of $err are displayed if there are any errors. If there are no errors, $err is empty, and script execution continues with the else clause.

Validation Warnings Always show all the warning messages that relate to the submitted data straight away. You should give your users the opportunity to correct their errors all at one time.

One obvious limitation of this approach is that you cannot pick which fields require a value; every posted field must have been completed. You could improve upon this by supplying a list of required fields in the script, and by using an associative array, you can also provide a label for each field to display in the warning message:

<?php
if ($_POST){
$required = array("first_name" => "First name",
"email" => "Email address",
"telephone" => "Telephone number");
foreach($required as $field => $label) {
if (!$_POST[$field]) {
$err .= "$label is a required field <br>";

}
}
echo $err;
} else {
echo "boo";
}

?>
<form method = "post">
First name : <input type="text" name="first_name" value="<?php echo $_POST['first_name']; ?>"/><br />
Email address : <input type="text" name="email" value="<?php echo $_POST['email']; ?>" /><br />
Telephone : <input type="text" name="telephone" value="<?php echo $_POST['telephone']; ?>" /><br />
<input type="submit" value="Submit"/>
</form>


views 4583
  1. Add New Comment