Validating POST fields the easy way

Validating POST data from a form is a common requirement for a developer. If the number of form fields are few than the validation is a small matter. But the case is different when the form contains more than 15 or 20 fields and some of the fields are mandatory. The following code will give you an idea of how to easily validate mandatory fields, whatever the number of fields.

The first step is to prefix a ‘c_’ or any other character of your choice to a form field that is mandatory. For example I’ve prefixed a ‘c_’ for the email field below.

Once we have added the required prefix we can check for them using the following code.

/* Initialize $_SESSION variables to hold errors and form variables */
$_SESSION['formVars'] = array();
$_SESSION['errors'] = array();

/* Copy all $_POST variables to $_SESSION['formVars'] */
foreach($_POST as $varname=>$value) 
     * For form elements that are compulsory check 
     * to see if they are empty. To ease this ,form 
     * elements that are compulsory have a 'c_' prefix added,
     * we can use that to parse the compulsory fields.
     /* Get the field prefix */
    $prefix = substr($varname, 0, 2);
    if(empty($_SESSION['formVars'][$varname]) && $prefix == "c_")
        $_SESSION['errors'][$varname] = substr($varname, 2, strlen($varname) - 2) . " field cannot be empty";

Now it doesn’t matter how many form fields you have, the code remains the same. You can extend the idea for other validation purpose. For example you can add a double prefix like ‘ci_” to indicate that the field is mandatory with a integer datatype and make the corresponding change in the validation code.

6 thoughts to “Validating POST fields the easy way”

  1. Hey there. Why not use PHP’s built-in ability to automaticaly create arrays from submitted data?



    $form_data = $_POST[‘c’];

    Using an array, there’s no need to loop through your submitted data to find fields with a prefix.

  2. I think in this area, there oh… about 7368 different ways.

    Typically, I go for this model:

    $v )
    if( ! ereg( $v , $_POST[$k] ) )
    $errors[$k] = “INVALID…”;


  3. Sorry you comment system hates me… 🙁

    $regs[‘user_name’] = “^[a-zA-Z][a-zA-Z]*$”;
    $regs[‘user_fname’] = “^[a-zA-Z][a-zA-Z]*$”;

    foreach( $regs as $k => $v )
    if( ! ereg( $v , $_POST[$k] ) )
    $errors[$k] = “INVALID…”;

  4. Hey… Do you really think it could be safety?
    What if I edit HTML source and send it to server? just using mozilla firebug extension – its the easiest way.

    I think all data must be validate on a server side.

Leave a Reply

Your email address will not be published.