Helpful Information
 
 
Category: Coding tips & tutorials threads
Concise PHP Form Validation

I made a neat little PHP function today which does error message handling, and I figured I'd share:


<?php
function check_posts() {
$found = array();
foreach ($_POST as $x => $y) {
$conditions = array("first" => (strlen($y) < 5), "last" => (strlen($y) < 2),
"email" => (!filter_var($y, FILTER_VALIDATE_EMAIL)), "password" => (strlen($y) < 5),
"password_check" => ($_POST["password_check"] != $_POST["password"]));
$errors = array(
"first" => "fname less then 5 ", "last" => "last name less then 2", "email" => "invalid email",
"password" => "pass less than 5", "password_check" => "second pass didnt match first");
if ($conditions[$x]) $found[] = $errors[$x];
}
$i = 1; if (count($found) > 0) {
foreach ($found as $z) { echo "<p>$i. $z</p>"; $i++; }
} else {
echo "passed validation.";
//validation code
}
}
?>

The red area contains the conditional statement which you would want to validate, ie: empty($country), or something. If it returns true then you have an error.

The blue area defines the corresponding messages.

These two areas are organized by post names (easiest way I thought).

After some thought I also decided to share the initial testing code:


<?php
function check_posts() {
$found = array();
foreach ($_POST as $x => $y) {
if ($x == "check") break;
$conditions = array("first" => (strlen($y) < 5), "last" => (strlen($y) < 2),
"email" => (!filter_var($y, FILTER_VALIDATE_EMAIL)), "password" => (strlen($y) < 5),
"password_check" => ($_POST["password_check"] != $_POST["password"]));
$errors = array(
"first" => "fname less then 5 ", "last" => "last name less then 2", "email" => "invalid email",
"password" => "pass less than 5", "password_check" => "second pass didnt match first");
if ($conditions[$x]) $found[] = $errors[$x];
}
$i = 1; if (count($found) > 0) {
foreach ($found as $z) { echo "<p>$i. $z</p>"; $i++; }
} else {
echo "passed validation.";
//validation code
}
}
?><html>
<head>

</head>
<body>
<form action="" method="post">
<p>First name: <input type="text" name="first"></p>
<p>Last name: <input type="text" name="last"></p>
<p>Email: <input type="text" name="email"></p>
<p>Password: <input type="password" name="password"></p>
<p>Re-type password: <input type="password" name="password_check"></p>
<p><input type="hidden" name="check" value="c"><input type="submit" value="Send"></p>
</form>
<?php
if (isset($_POST["check"])) {
check_posts();
}
?>
</body>
</html>

The blue code is to skip the hidden input element "check".










privacy (GDPR)