PHP Form Validation

1
2499

Today we will learn about validation of the form elements in this PHP Form Validation tutorial.

While entering input in the form, user can enter wrong input may be by mistake or purposefully. This will create problem for processing the form. The programmer should not rely on user or should not have full faith in user that he/she will enter correct data only. To avoid any wrong input data it is programmer’s responsibility to stop the user from putting any wrong input. This can be done using validations for the form input elements. This will not allow the user to put letters where numbers are required and vice-a-versa.

  • What is Validation?
    • Validation is a task used to check the input entered by user in a form, to avoid errors in the output.
    • When the user clicks on submit button after filling the form, the input is first validated and then it is processed further.
    • If the input entered by user is not correct, the user is again asked to enter the correct information by giving error messages instead of processing it.
  • Types of Validation:
    • There are 2 types of validations:
      1. Client-Side Validation:
        • When the validation is performed on client machine, it is called as client-side validation.
        • Here all information is not sent to server for validation, instead it is validated at client-side itself.
        • This is a fast method of validation and at the same time it minimizes the unnecessary load on server.
      2. Server-side Validation:
        • When the validation is performed on server, it is called as server-side validation.
        • The data is sent to the server for validation and if any error occurs in validation, it is sent to the client to correct the input.
        • Validation done at server-side is reliable and secure.
  • Validation functions:
    • There are 2 validation functions:
      1. Basic Validation:
        • The form is checked against every form field, whether the input is entered in every field or not.
      2. Data Format Validation:
        • It checks if the form element contains the correct data.
        • It checks whether the data is in correct format such as of email-id etc.
        • It checks the field requiring numbers has numbers only; the field requiring string has string only, etc.
  • Validation:
    • Let us demonstrate the validation with the help of an example and understand the code.
    • There are 2 methods to validate the page:
      1. Validate the input by checking it in the same page at client-side by using $_SERVER[“PHP-SELF”] in the action attribute of the form.
      2. Validate the input by sending it at the server-side by putting the desired page URL in the action attribute of the form.
    • To demonstrate it, let us create a new folder named Validation in the htdocs folder in xampp folder in C drive. Then open a new notepad++ document and save it as index.php in the newly created Validation folder.
    • The code for a simple HTML form is given below:
    • Here we have a customer details from created with text fields for name, city, state, mobile number, textarea for address and a button SAVE.
    • We are going to validate this form.
    • The form above has post method and the action attribute has the value
    • In this above statement the statement $_SERVER[“PHP_SELF”] takes the data entered by user in the form to the same page.
    • This $_SERVER[“PHP_SELF”] is enclosed in htmlspecialchars() function. The task of this function is to convert all the special characters like < and > to html entities like < and >
    • This prevents the chances of exploitation of the code by insertion of some other HTML or javascript code in the form.
    • We can also give the URL of another page in the action attribute and validate the input in that page.
    • Here we are validating it in the same page.
    • Let us first decide as to what should be done in validation.
    • We want the user to enter his name, city, state and mobile number compulsorily.
    • Next the fields of name, city and state should contain only letters and the mobile number field should contain numbers and its length should be 10.
    • In this tutorial we are just going to see how an error is generated to prompt the user to correct his mistake. So just pay attention to the code given below:
    • The code given below contains the whole code (validation as well as HTML form code) in index.php page.
    • This code is written in a very dimple format just to make you understand the concept of validation.
    • The following code which is written above the html form code contains the validation code. It is shown below:
    • Let us understand this validation code.
    • Here, we know that we want the name, city, state and mobile number as compulsory (required fields), the name, city and state to be strings and mobile number to be numeric with 10 digits in it.
    • If any input is not according to our wish, an error message is to be shown immediately.
    • So we have declared a variable named $errormsg which is initialized to the empty string initially. This will store all the error messages in it. Different variables can also be used to store different error messages, but it will be impossible for validating a large number of input fields.
    • A Boolean variable $valid is initialized to false initially. This variable is used to indicate that our form is validated completely. How? If $valid variable has value false, it will tell us that our form is not yet validated completely and if $valid variable has value true, it will tell us that yes the complete form has been validated.
    • After this we have a if statement shown below:
    • Here it is checked that if form has been submitted (saved in our case) with POST method.
    • If this condition evaluates to true, then only this if block will execute. i.e. if $_SERVER[“REQUEST_METHOD”]==”POST” condition evaluates to true, then only the $_POST superglobal array variable will contain all values entered by user.
    • We know that the $_POST superglobal array variable accesses the input field values with their names as shown below:
    • Name –> $_POST[“name”];
      Address –> $_POST[“addr”];
      City –> $_POST[“city”];
      State –> $_POST[“state”];
      Mobile –> $_POST[“mob”];

    • So we have accessed and stored these values in variables as shown below:
    • Instead of storing in variables these values can also be used directly in the code.
    • Next we have checked the name to see whether it is empty, because it is a required field.
    • The code is shown below:
    • The function empty() is used to see whether the field is empty or not.
    • If the field is empty, an error message is concatenated to the variable $errormsg.
    • The concatenation of error messages is done with (.=).
    • This has the effect of concatenating the error message already present in the $errormsg variable and the other error message given after (.=). i.e.
    • The error statement after string concatenation operator contains a class error as shown below:
    • This class is styled with red colour in the head section, so that error message appears in red colour.
    • If name field is empty, error will be stored in $errormsg and $valid variable will be made false to indicate that the field is not validated.
    • Now if the name field is not empty, the else part will execute.
    • Here we check if the value entered in the field is string or not using is_string() function as shown in the if statement below:
    • If the input is a string the $valid variable is made true to indicate that this field is validated.
    • But if the input is not a string, an error message is stored in $errormsg variable and $valid variable is made false.
    • Similar validation is done for city and state.
    • Next is the mobile number, it should contain numbers and should have 10 digits in it.
    • The mobile number is also a required field, so it is also checked for the empty test using empty() function.
    • If the mobile number field is not empty, its length is checked first using strlen() function and stored in $len variable.
    • We used here strlen() function because anything entered in a text field is considered as string only.
    • Next an if statement checks whether the mobile number has only numbers using the is_numeric() function and it also checks whether the length obtained in $len variable is equal to 10 or not.
    • If this condition is true, the $valid variable is set to true otherwise and error message is stored in $errormsg variable and $valid variable is set to false.
    • After checking all this, it is checked if variable $errormsg is not empty. If it is not empty, all the error messages are shown.
    • If there is no error, no error message will be shown and our $valid variable might have been already set to true.
    • In this situation after validating whole form, we are directed to the next page using the statement
    • header() function redirects us to the page specified in it. We will be redirected to success.php page.
    • The code in success.php page which is saved in Validation folder itself is given below:
    • If errors are present, we will not be redirected to next page.
    • The output of the form is shown below:
    • form
      fig 1

    • Now click on the SAVE button without entering the input, you will see the following error messages:
    • errors_on_submitting_witout_entering_input
      fig 2

    • Now let us enter the input. But we will not enter any input in required field and enter an improper mobile number and then click on the SAVE button. The output is shown below:
    • half_filled_form
      fig 3

    • Here we see that we get an error message that “State is compulsory” and “Mobile number should be in number format with 10 digits in it.” This is because we did not enter the state and entered an improper data in the mobile number field.
    • Now let us fill the form correctly as shown below:
    • completely_filled_form
      fig 4

    • Now let us click on SAVE button. The output obtained is shown below:
    • success_page
      fig 5

    • Since there was no error, we are redirected to success.php page after clicking on SAVE button.

Thus we studied how to check an input in the input field for its validity and how to show errors. We will see validation of some more input fields in the next session.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here