Pin Me

PHP Code Validators

written by: S. R. Obbayi•edited by: Michele McDonough•updated: 6/30/2011

The PHP Validation Script is a complete set of rules by which you can add server-side validation to the forms easily and quickly. Read the full article to know the implementation of the Code validators and there's also a demo form for your better understanding.

  • slide 1 of 1

    PHP Validation Code

    The PHP Code Validators or more specifically the PHP Validation Script is a complete set of rules by which you can add server-side validation to the forms easily and quickly. The main purpose of PHP Code Validators is that the script checks all the values that has been entered into the form by the user. If it does not matches the specified criteria, that is if the user has missed out any value or the entered email address is non-existing, the code validators returns the user to the original form with the list of all the wrong entries. That really sounds great, however it requires PHP 4 or later versions.

    How to add PHP Code Validation

    The first step is to download and upload the PHP validation script (validation.php) to your web server and include() or require() that file through PHP in the form page.

    Next step is to direct the form to submit its contents to itself using action="" attribute. Once the form clears the validation rules successfully, you can then redirect to whatever page via PHP. In case if it fails, you can directly output the errors in the form page so that the user can fix it.

    Note that the form-specific validation rules should be added to the top of your form page before the opening <html> tag. These validation rules are a list or an array that says which form fields are to be validated and in what way. It also says about the errors that should be displayed to the user if they do not fill it properly.

    The final step is to add some display code into the page, which will be responsible to output, if any errors occur. See the following code for this;

    <?php

    // if $errors is not empty, the form must have failed one or more validation

    // tests. Loop through each and display them on the page for the user

    if (!empty($errors))

    {

    echo "<div class='error'>Please fix the following errors:\n<ul>";

    foreach ($errors as $error)

    echo "<li>$error</li>\n";

    echo "</ul></div>";

    }

    ?>