We begin with a sample HTML form.

Fields marked (*) are required.





Now for the all-purpose script. *

* Enter your phone number: * *

* * * * $method is "get" * $key is "phone" * $val is whatever phone number the user entered, like "800 123 4567". * * $_GET["phone"] = "800 123 4567" thus $method[$key] = $val * * What if we had provided a description too? * * * * * $method is still "get" * $val is still "800 123 4567" * * But we want to use value of "phone_desc" instead of "phone" to * send to our custom validation function. All we have to do is * append "_desc" to "phone". Normally $key = "phone", so ... * * $method[$key . "_desc"] * * will give us "Phone Number" instead of just "phone" (the name * attribute of our first text input) to use in our error message. */ foreach($method as $key => $val) { /* $func is the name of the custom validation function. $func can be * changed here, just make sure that if you want to validate * that element's input there is a matching function name. * * From our phone number example above, would have to have a function * named validate_phone($val, $method[$key . "_desc"]). */ $func = "validate_" . $key; if(function_exists($func)) { /* Send the custom function the user data to be validated, * along with the field's description (if one was provided) * for use in an error message. Otherwise, send the entered data * as usual, but this time just the element's name attribute for use * in an error message. */ if(isset($method[$key . "_desc"])) $result = $func($val, $method[$key . "_desc"]); else $result = $func($val, $key); if($result !== true) { add_error($result); $process = false; } } } } ?>
Now for the implementation, where we specify how our form handled the data, validate the data (beyond if it was empty) and output any error messages. to work with CSS this way */ echo "
\n"; echo "\n"; echo "
\n"; /* There are newline ("\n") characters so that in our HTML code everything isn't on just one long line */ } /* Here is where we really validate our data. The names of the functions here must match $func in the all-purpose script. How you choose to validate data is completely up to you. The all-purpose script only cares if these functions return true or false. I'm using another byteMyCode snippet as an example of validating e-mail. You can find it here: http://bytemycode.com/snippets/snippet/378/ . Since I'm only providing an email function, the other required fields have only been checked that they aren't empty. */ validate_email($data, $description) { list($User, $Domain) = explode("@", $data); $result = checkdnsrr($Domain, 'MX'); if(result) return true; else return "Your " . $description . " is invalid!"; ?>