PHP Form Validation Script

It is very essential to have the input to your form validated before taking the form submission data for further processing. When there are many fields in the form, the PHP validation script becomes too complex. Moreover, since you are doing the same or similar validation for most of the forms that you make, just too much of duplicate effort is spent on form validations.

Note: You can make web forms quickly with Simfatic Forms. Simfatic Forms helps you to make complete, feature rich web forms and get it online quickly. Read more here.

About this generic PHP form validation script

This generic PHP form validator script makes it very easy to add validations to your form.

We create and associate a set of “validation descriptors” with each element in the form. The “validation descriptor” is a string specifying the type of validation to be performed. For example, “req” means required, “alpha” means allow only alphabetic characters and so on.

Each field in the form can have zero, one or more validations. For example, the input should not be empty, should be less than 25 chars, should be alpha-numeric, etc

You can associate a set of validation descriptors for each input field in the form.

Download the PHP form validation script

You can download the PHP form validation script below:
php-form-validator.zip The zip file contains the form validation script formvalidator.php, documentation and usage samples.

Using the PHP form validation script

  1. Include formvalidator.php in your form processing script
  2. require_once "formvalidator.php"
  3. Create a FormValidator object and add the form validation descriptors.
  4. $validator = new FormValidator();
    $validator->addValidation("Name","req","Please fill in Name");
    $validator->addValidation("Email","email",
    "The input for Email should be a valid email value");
    $validator->addValidation("Email","req","Please fill in Email"); 
    

    The first argument is the name of the input field in the form. The second argument is the validation descriptor that tells the type of the validation required. The third argument is the error message to be displayed if the validation fails.

  5. Validate the form by calling ValidateForm() function
  6. if(!$validator->ValidateForm())
    {
        echo "<B>Validation Errors:</B>";
        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
            echo "<p>$inpname : $inp_err</p>\n";
        }
    }
    

Example

The example below will make the idea clearer

<?PHP
require_once "formvalidator.php";
$show_form=true;
if(isset($_POST['Submit']))
{
    $validator = new FormValidator();
    $validator->addValidation("Name","req","Please fill in Name");
    $validator->addValidation("Email","email",
"The input for Email should be a valid email value");
    $validator->addValidation("Email","req","Please fill in Email");
    if($validator->ValidateForm())
    {
        echo "<h2>Validation Success!</h2>";
        $show_form=false;
    }
    else
    {
        echo "<B>Validation Errors:</B>";

        $error_hash = $validator->GetErrors();
        foreach($error_hash as $inpname => $inp_err)
        {
          echo "<p>$inpname : $inp_err</p>\n";
        }
    }
}

if(true == $show_form)
{
?>
<form name='test' method='POST' action='' accept-charset='UTF-8'>
Name: <input type='text' name='Name' size='20'>
Email: <input type='text' name='Email' size='20'>
<input type='submit' name='Submit' value='Submit'>
</form>
<?PHP
}//true == $show_form
?>

Adding Custom Validation

If you want to add a custom validation, which is not provided by the validation descriptors, you can do so. Here are the steps:

  1. Create a class for the custom validation and override the DoValidate() function
  2. class MyValidator extends CustomValidator
    {
        function DoValidate(&$formars,&$error_hash)
        {
            if(stristr($formars['Comments'],'http://'))
            {
                $error_hash['Comments']="No URLs allowed in comments";
                return false;
            }
        return true;
        }
    }
    
  3. Add the custom validation object
  4. $validator = new FormValidator();
    $validator->addValidation("Name","req","Please fill in Name");
    $validator->addValidation("Email","email",
     "The input for Email should be a valid email value");
    $validator->addValidation("Email","req","Please fill in Email");
    $custom_validator = new MyValidator();
    $validator->AddCustomValidator($custom_validator);
    

The custom validation function will be called automatically after other validations.

Table of Validation Descriptors

Here is the list of all validation descriptors:

Validation DescriptorUsage
reqThe field should not be empty
maxlen=???checks the length entered data to the maximum. For example, if the maximum size permitted is 25, give the validation descriptor as “maxlen=25”
minlen=???checks the length of the entered string to the required minimum. example “minlen=5”
alnumCheck the data if it contains any other characters other than alphabetic or numeric characters
alnum_sAllows only alphabetic, numeric and space characters
numCheck numeric data
alphaCheck alphabetic data.
alpha_sCheck alphabetic data and allow spaces.
emailThe field is an email field and verify the validity of the data.
lt=???
lessthan=???
Verify the data to be less than the value passed. Valid only for numeric fields.
example: if the value should be less than 1000 give validation description as “lt=1000”
gt=???
greaterthan=???
Verify the data to be greater than the value passed. Valid only for numeric fields.
example: if the value should be greater than 10 give validation description as “gt=10”
regexp=???Check with a regular expression the value should match the regular expression.
example: “regexp=^[A-Za-z]{1,20}$” allow up to 20 alphabetic characters.
dontselect=??This validation descriptor is for select input items (lists) Normally, the select list boxes will have one item saying ‘Select One’. The user should select an option other than this option. If the value of this option is ‘Select One’, the validation description should be “dontselect=Select One”
dontselectchkThis validation descriptor is for check boxes. The user should not select the given check box. Provide the value of the check box instead of ??
For example, dontselectchk=on
shouldselchkThis validation descriptor is for check boxes. The user should select the given check box. Provide the value of the check box instead of ??
For example, shouldselchk=on
dontselectradioThis validation descriptor is for radio buttons. The user should not select the given radio button. Provide the value of the radio button instead of ??
For example, dontselectradio=NO
selectradioThis validation descriptor is for radio buttons. The user should select the given radio button. Provide the value of the radio button instead of ??
For example, selectradio=yes
selmin=??Select atleast n number of check boxes from a check box group.
For example: selmin=3
seloneMakes a radio group mandatory. The user should select atleast one item from the radio group.
eqelmnt=???compare two elements in the form and make sure the values are the same For example, ‘password’ and ‘confirm password’. Replace the ??? with the name of the other input element.
For example: eqelmnt=confirm_pwd

Also See:

PHP Form Validation Tutorial

Comments on this entry are closed.

  • I think that some regexp for Validation Descriptor are false.

    The regexp for alnum_s is [^A-Za-z0-9 ].
    In the description, alnum_s “Allows only alphabetic, numeric and space characters.”
    If we check the regexp in regexbuddy, it says :
    Match a single character NOT present in the list below
    A character in the range between €œA€ and €œZ€ «A-Z»
    A character in the range between €œa€ and €œz€ «a-z»
    A character in the range between €œ0€ and €œ9€ «0-9»
    The character €œ €

    The right regexp is : ^[A-Za-z0-9 ]+$

    I think we must have in the ValidateCommand function :

    alnum ^[A-Za-z0-9]+$ Allows only alphabetic and numeric characters
    alnum_s ^[A-Za-z0-9 ]+$ Allows only alphabetic, numeric and space characters
    num ^[0-9]+$ Allows only numeric characters
    alpha ^[A-Za-z]+$ Allows only alphabetic characters
    alpha_s ^[A-Za-z ]+$ Allows only alphabetic and space characters

    • Need also to change, as said in a previous post, the test_datatype function :

      function test_datatype($input_value, $reg_exp) {
      if(preg_match(“/”.$reg_exp.”/”, $input_value)) {
      return true;
      }
      return false;
      }

    • Wrong. One can either test against negative case or positive case.
      Please test it before posting the code.

      • You’re right, the regexp are good.

        What i want to say is that the regexp you provide and the explanation are not similar.
        [^A-Za-z0-9 ] does not allow alphabetic, numeric and space.
        The explanation you give is “Allows only alphabetic, numeric and space characters”.

        • Yes, I can confirm that “alnum” (and probably “alum_s”) does NOT work.

          • My bad. alnum DOES work, but not after you remove depreciated code as per Dave F’s fix… make sure you update all regex statements with “/”.

  • When you have several addValidation, only the last error message is displayed.
    In this example, only “Message 3.” is returned.

    $validator->addValidation(“toto”, “numeric”, “TOTO”, “message 1.”);
    $validator->addValidation(“toto”, “gt=100”, “TOTO”, “Message 2.”);
    $validator->addValidation(“toto”, “lt=1000”, “TOTO”, “Message 3.”);

    To have all message displayed, just change the ValidateForm function like this :

    if ($this->error_hash[$val_obj->variable_name] != “”) {
    $this->error_hash[$val_obj->variable_name] .= “”.$error_string;
    } else {
    $this->error_hash[$val_obj->variable_name] = $error_string;
    }

  • Hi, the custom validator doesn’t seem to work, even in the example file?

  • You may want to update your validate_email function by migrating your regexp check from ereg to preg_match. Otherwise you’ll get ereg deprecated errors if you’re running a high enough php version.

  • Ereg, eregi and Preg_match Are deprecated… How can we solve it?

    Thx

  • Can any 1 tell that we can use more than 1 Validation Descriptors for single field?

    • yes, you can.

  • thanks for the script, works great apart from the fact it doesn’t to go thank-you.php when it has been submitted.

  • Hey guys, if you are getting deprecation warnings you just need to make two changes to the formvalidator.php file.

    Line 228: Simply change ereg(etc…) to preg_match(etc…)

    Line 237: Change eregi(etc..) to preg_match(etc…) BUT you also must add a / to the beginning and end of the regular expression being checked. As well, to make the check case insensitive (which eregi does) simply add an ‘i’ after the / you put at the end of the regular expression. Line 237 should look like this now:

    return preg_match(“/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i”, $email);

    • Great job! This worked fine for me.

      • Additionally you need to update the other regular expressions in the document by adding a “/” (without quotes) to the beginning and end of them… If you don’t ALNUM, etc, will not work properly.

  • Hi all!
    I want insert valid data in database, but i don’t undertand how do it. Please told me how.
    Part of code:
    $validator->addValidation(€œname€, €œreq€, €œPlease fill in Name€);
    …..
    if($ validator->ValidateForm()){
    $query = €˜insert into mytable (name) values ($POST[“name”])’;
    }
    …..

  • how to group check boxes ??
    need example here >>>>

  • Thanks Dave F, your little code updates worked a treat.

    Author of the script, hows about you update the download?

  • Hi, when validating arrays as required there is a warning. This should sort that out:

    function validate_req($input_value, &$default_error_message, $variable_name) {
    $bret = true;
    if (is_array($input_value)) {
    if (max(array_map(‘strlen’, $input_value)) <= 0) {
    $bret = false;
    $default_error_message = sprintf(E_VAL_REQUIRED_VALUE, $variable_name);
    }
    } else if (!isset($input_value) || strlen($input_value) <= 0) {
    $bret = false;
    $default_error_message = sprintf(E_VAL_REQUIRED_VALUE, $variable_name);
    }
    return $bret;
    }

  • Hi,
    what if I want to check validation for a field but I dont want it to be a compulsory field, what should be done in that case? I was refering client side validation script.
    Gr8 work
    Thanks

  • If you want it to accept variables rather than $_POST or $_GET data (which seems like a pretty crappy way of doing things… For example, you can’t sanitize the data before you process it) comment out the following lines (starting at 157):

    if(isset($formvariables[$validatorobj->variable_name]))
    {
    $input_value = $formvariables[$validatorobj->variable_name];
    }

    And just replace with the following line:

    $input_value = $validatorobj->variable_name;

    • Actually skip that, thanks to the weird way the data is processed, it doesn’t seem to work properly.

  • Hi there,
    when i click on submit if there is any filed which is not entred and if it is required all the other entred fields are clearing.please advice how to keep the entered values ?

    tnx,
    Nagaraju.

    • example for Nagaraju:

      <input type="text" name="username" value="”/>

      • input type=”text” name=”height” id =”height” value=”(php open tag) if (isset($_POST[‘height’]) echo $_POST[‘height’]; (php close tag)”/>

  • Request: Can you please update this so that it accepts VARIABLES instead of $_POST and $_GET. Accepting only those two leads to very poorly structured code, and your class is otherwise excellent. Thanks.

  • Very nice and useful script.

    Just a tip, only for PHP 5+
    You can implement the PHP filters, to get more power of this script;

    http://www.php.net/manual/en/book.filter.php

  • Orig and modified forms work great in Firefox and Safari.
    IE 9 croaks – even if all I did to your script is put my email address in – hit submit, and keeps putting in new captcha code – please, what am I doing wrong?
    http://tsa-usa.org/x/contactform.php
    Thank you

  • Hi, when I run your code without any “action” in the form, it seems OK. however, when I want to add some “action” to the form. The code seems to run the action first instead of doing the form validation first. How can I solve the problem?

  • Thanks a lot dude..