Form Validation Assistance

Posted this before but the code had a bad format. 'm trying to fix this so the the values are only invalid if they do not match the Regex. What should I fix?

<?php ini_set("display_errors", 1); // Turns on error reporting for this program. error_reporting(E_ALL | E_STRICT); //Show all possible problems to browser. $elements = array( 'selected_play' => "", 'numberoftickets' => "", 'first-name' => "", 'last-name' => "", 'address' => "", 'city' => "", 'state' => "", 'zip' => "", 'email' =>"", 'creditcard' => "", 'creditcard-number' => "", 'cvv-number' => ""); $invalidElements = array(); foreach (array_keys($elements) as $newKey) { $value = trim($_POST[$newKey]); /* I think I need to fix this some how*/ if (!isset($value)) { } if(empty($value)){ $invalidElements[$newKey] = $invalid_error_message; preg_replace("/\-/", " ", $value); } /* Not sure if $newKey should be placed here */ switch ($newKey) { case 'first-name': if (!preg_match("[a-zA-Z]{3,30}", $value)) { $invalid_error_message = "First Name"; } else { return true; } break; case 'last-name': if (!preg_match("[a-zA-Z]{3,30}", $value)) { $invalid_error_message = "Last Name"; } else { return true; } break; case 'address': if (!preg_match("d{1,3}\s[a-zA-Z]{2,30}\s[a-zA-Z]{2,10}", $value)) { $invalid_error_message = "Address"; } else { return true; } break; case 'city': if (!preg_match("[a-zA-Z]{3,30}", $value)) { $invalid_error_message = "City"; } else { return true; } break; case 'state': if (!preg_match("/^\w{2}$/'", $value)) { $invalid_error_message = "State"; } else { return true; } break; case 'zip': if (!preg_match("/^[0-9]{5}(?:-[0-9]{4})?$/", $value)) { $invalid_error_message = "Zip Code"; } else { return true; } break; case 'email': if (!preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)* (\.\w{2,3})+$/",$value)) { $invalid_error_message = "Email"; } else { return true; } break; case 'creditcard-number': if (!preg_match("/(d{15,16})/", $value)) { $invalid_error_message = "Credit Card Number"; } else { return true; } break; case 'cvv-number': if (!preg_match("/(d{3,4})/", $value)) { $invalid_error_message = "CVV number"; } else { return true; } break; } $elements[$newKey] = $value; } ?> <?php echo "

The following errors were found in the purchase form. Please return, and fill out the form again.

"; /*Not sure if I have the right statement here */ foreach ($invalidElements as $value => $invalid_error_message) { echo "

The form is missing a field: $invalid_error_message

"; } if (count($invalidElements) > 0){ echo "

Use your browser's back button to return for correction.

"; } ?>

Well, your code is a bit mixed up. First, you really do not need all of the array and case handling.
Unless you are attempting to create a validation “class” to handle validating unknown inputs.

My thoughts on this are you have a form that you know everything on it and what fields are there.
You know which fields are required and what is allowed to be inside each field. Why not just validate
each field and create a better way of reporting your errors.

Right now, your code only shows one error at a time. (Actually it will show only the last error.)
Most programmers “stack” errors for displaying them. So, instead of $error_message = “some message”; …
You would do it more like $error_message .= “some message
”; (Note the period before the = )
The “.=” means append the data to the end of the variable instead of equal to the data. And, you have
to add the
at the end so the messages are on separate lines. That is one improvement.

Now, this is usually how I handle validation of form inputs. First I check for the missing ones that are
required. If they are missing I note it. Then, if there, I validate the data in each noting bad ones.

Something in general like this:
[php]
// First check for the submit button being pressed…
if($_POST[‘submit_button’]!="") {
// Grab all the fields we want to use and validate (Just a sample, include all of yours)
$name = $_POST[‘name’];
$comment = $_POST[‘comment’];

	//  Validate inputs
	$error_message = "";  //  Start with no error messages...
	if (!preg_match("/^[a-zA-Z0-9. ]*$/", $name)) $error_message .= "<br />Name must be only letters, numbers, periods and whitespace.";
	if (!preg_match("/^[a-zA-Z0-9. ]*$/", $comment)) $error_message .= "<br />Comments must be only letters, numbers, periods and whitespace.";

            //  If errors say so, if no errors process data into database...
            if($error_message=="") {
                     echo "Your form was processed....";
                     //  Here save into database or whatever...
            } else {
                     echo "Errors were found in your form:<br />";
                     echo $error_message;
            }
    }

[/php]
This is just a quick sample to give you an idea on how I would do this process. Much simpler and easy
to follow. Just remember that if you load all your fields into arrays and then process the arrays that you
are making the server work hard to handle all of that. It is not a problem with one user online, but, if
your user list is 50,000 users, there would be a lot of processing time wasted on loading and parsing
thru arrays of form entries. Also, remember that you already have an ARRAY of FIELDS that were sent
from the form. It is called $_POST[] ! This is a built-in array that has all of the fieldnames in it along with
their values.

Hope this helps!

Oh, one more thing. Please place your code inside of the PHP tags so we can select them easier… Thanks!

Sponsor our Newsletter | Privacy Policy | Terms of Service