PHP 5 Form Validation

Required field will check whether the field is filled or not in the proper way. Most of cases we will use the * symbol for required field.

Validation means check the input submitted by the user. There are two types of validation are available in PHP. They are as follows −

  • Client-Side Validation − Validation is performed on the client machine web browsers.
  • Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine.
  • Validate Form Data With PHP

    The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.

    When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:

    - this would not be executed, because it would be saved as HTML escaped code, like this:


    The code is now safe to be displayed on a page or inside an e-mail.

    We will also do two more things when the user submits the form:

  • Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
  • Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
  • The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).

    We will name the function test_input().

    Now, we can check each $_POST variable with the test_input() function, and the script looks like this:

    Example -