Errors...

I am always running into situation where I need to check for empty fields or other validation that needs to have errors return to the user so they know what is wrong before submitting form. What I normally do, is as follows:

[php]<?php

$name = $_POST[‘name’];
$state = $_POST[‘state’];
$errors = array();

if(empty($name))
{
$errors[] = “You forgot to fill in your name!”;
}

if(empty($state))
{
$errors[] = “You forgot to fill in your state!”;
}

if(!empty($errors))
{
for($i = 0; $i < count($errors); $i++)
{
?>

<?php echo $errors[$i]; ?>

<?
}
}
?>[/php]

Of course I do a little more formatting and such to make errors match the sites specific look and feel, but anyway, just was wondering if there was an easier way then writing an if statement for each field in the html form?

I haven’t thought of a better one or seen one as of yet.

I always keep extensibility in mind:

[php]
$errors = array();
$expectedFields = array(“field1”, “field2”, “field3”, “field4”, “field5”);
$mandatoryFields = array(“field2”, “field5”);

for ($i = 0; $i < count($expectedFields); $i++) {
$expectedFields[$i] = “”;
if (isset($_POST[$expectedFields[$i]])) {
$expectedFields[$i] = $_POST[$expectedFields[$i]];
// MORE CHECKS HERE
}

if (in_array($expectedFields[$i], $mandatoryFields) && $expectedFields[$i] == “”) {
$errors[] = “Forgot a mandatory field!”;
}
}

for ($i = 0; $i < count($errors); $i++) {
// DISPLAY ERROR MESSAGES
}

if (count($errors) == 0) {
// CONTINUE PROCESSING INPUT
}[/php]

This is especially handy when dealing with large forms (lots of input boxes) or forms that change shape. Besides that, it’s reusable over different forms :wink:

Cool, thanks Zyppora, I will definatly keep this in mind the next time I do any form. I think that is the number one time sucker on most jobs is the
Dummy-Proofing (AKA: Stupid-Proofing) of the forms I have to do. :)

This looks like it could save lots of time!

Sponsor our Newsletter | Privacy Policy | Terms of Service