You are here: Home » All Posts » PHP Form » PHP Form Validation Script

PHP Form Validation Script

in PHP Form

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
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

No related posts.

{ 138 comments }

Nick October 12, 2011 at 4:15 pm

Michael, I think the problem causing selmin not to work is caused by a couple of things. One is that the type of the variable being checked isn’t retained when it isn’t set, so the count() check always returns 1, and the second thing is the minimum size check should be > 0 and not > 1.
If you find line 155 and replace
$input_value =”";
with

if (is_array($formvariables[$validatorobj->variable_name])) {
$input_value = array();
} else {
$input_value =”";
}

and then on line 509 change the line
if($min_count > 1)
to
if($min_count > 0)
it should work.
I haven’t exhaustively checked this, but it works for all the tests I have done so far.
Good luck
 

Nick October 13, 2011 at 9:56 pm

I think the suggested change for
$input_value = ”;
can be reduced to
$input_value = array();

dineo November 1, 2011 at 1:04 pm

am having problems with connecting and validating my forms please help me

Jason November 3, 2011 at 3:39 pm

How can I simply and easily add this to a page with a form on it and the send it to my processing script that converts it to csv?  My csv script works and the simple example for the validation works but then I don’t see any error messages.

SWETHA November 15, 2011 at 5:30 am

How to print the error messages in desired location?

KARTHI November 22, 2011 at 9:43 am

hi all,im beginner in php development, i have a doubt regrading concatenation of multiple text box , ex: we have date of birth month is a drop down box , year is a drop down box ,date is drop down box , and ma question is how do u validate this form ,,when u update in mysql???
can any clearly ma doubt

Scott November 29, 2011 at 9:13 am

Hi, I’m currently using your PHP validation script on a form I have built for a client and I do get an issue sometime where the error ‘Automated submission prevention: case 1 failed’ appears at the top of the form, I’m unsure what this error is for and exactly why it is appearing as mentioned it doesn’t happen all the time.
Any ideas would be greatly appreciated.

Thanks
Scott

venagt November 29, 2011 at 12:14 pm

simplest way req…

man December 1, 2011 at 8:44 am

thank you

Sdg December 1, 2011 at 6:04 pm

email is sent but error message pops up…. how to rectify this email me…..
Deprecated: Function eregi() is deprecated in /home/gosdgacc/public_html/go-sdga.co.cc/include/formvalidator.php on line 237

Deprecated: Function split() is deprecated in /home/gosdgacc/public_html/go-sdga.co.cc/include/class.phpmailer.php on line 470

Jean Paul December 8, 2011 at 9:39 am

replace eregi() function with preg_match() function and end pattern with ^. Hence the changes will be:
eregi(“^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$”, $email) become:
preg_match(“^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$^”, $email);

Damilola January 5, 2012 at 3:32 pm

please how do i join this forum?

Jean Paul December 8, 2011 at 5:02 pm

This the great topic as we always need the server side script.

Dan December 13, 2011 at 8:15 am

Hi,

In your examples (php-form-validator.zip) the file formvalidator.php has a character of white space after the closing PHP tag. This caused a header error as this was considered ‘output’. Anyway after 2 hours of trying to figure out why all of your form examples were not working deleting that white space fixed it. just thought I would let you know!

Daniel

Peter Chu December 15, 2011 at 9:34 am

hi, how can I use the script to check fields name like “name[1]“?

Bill December 23, 2011 at 12:47 am

supply an example of a radio button group.
It seems that having set up a a radio group with populated values and having added the logic at validation

$validator->addValidation(“radioButtonGroup”,”selone”,”make radio button selection”);

does not make proper validation. It does not make any validation at all.
Thank you

lydya December 24, 2011 at 1:37 am

i just wondering how to validated only email and url in form.

TotalNEWB December 31, 2011 at 4:42 pm

Well I’m completely baffled. This is my FIRST attempt at php validation… or any validation for that matter. I have no clue how this works, what to edit or how to custsomize it for my form. It looks like more experienced coders are having a tough time so I guess I have to move on and try something else. Thanks for posting this anyway. Maybe I can use it sometime when I’ve learned more.
If I had $50 bucks I’d buy Simfatic, cuz I sure as hell need it. Oh well.

prakash January 2, 2012 at 11:57 am

what if i have to check whether a passed string is URL or not.
If it is Url, its ok, if it is not url, i have to print a message.

senacle January 3, 2012 at 8:03 am

Hi,

In the error message, the variable name (the name of the field in the form) is displayed.
It’s sometime (everytime ?) not useful for the user.

So, i added a param which is “error_variable_name”, it’s the name thaht you want to show to the user (most of time, the label of the field).

Just change some code in the formvalidator.php like this :

function addValidation($variable, $validator, $error_variable_name, $error_message)
{
…..

$validator_obj = new ValidatorObj();
$validator_obj->variable_name = $variable;
$validator_obj->validator_string = $validator;
$validator_obj->variable_name_error = $error_variable_name;
$validator_obj->error_string = $error_message;
array_push($this->validator_array,$validator_obj);
…..
function ValidateForm()
{

foreach($this->validator_array as $val_obj)
{
….
$this->error_hash[$val_obj->variable_name_error] = $error_string;

….

And in your validation script, something like that :

$validator->addValidation(“name_people”, “req”, “Name of the people”, “Please fill in Name”);

Jonas Lagerwall January 3, 2012 at 10:20 pm

I wrote a form validator in case someone wants to check it out. The approach is slightly different from what is used here. It can be found on jform.lagerwall.net.

Cheers!

Comments on this entry are closed.

Previous post:

Next post: