In the last tutorial we have seen how to create FORM in HTML and display it in PHP file. But what if that data are not filled or not valid . For example if someone enter invalid email or other invalid  data.

For such cases, we will apply validation in FORM,  so valid and proper data will be entered and then will be displayed or used further.

Today we will see about required fields as well as apply validation on name, number and email data. In this example, Name, Number and Email are required fields and can not be empty and when you submit data without these data, it shows error messages.  With that Name field only allows alphabets and white spaces, Number field allows only numbers and email field must have proper valid email address.

HTML FORM ELEMENTS :

In this Code, we have defined form elements i.e. Textbox for Name, Phone Number and Email and they are required filed , and therefore we have put asterisk besides each. To display asterisk  and error message in red color ,  put it in span class. Here $Name_Error is a PHP variable used to display appropriate message. (Name is Required or Only Alphabets & White Spaces are allowed).

<tr><td> Enter Name   :  </td> <td> <input type="text" name="txtName">
    <span class="error"> * <?php echo $Name_Error;?></span>   </td></tr>


Likewise will do for other fields

<html>
<body>
<span class="error"> * Required Fields </span>
<form name="frm1"  action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">

<table border=1>
<tr><td> Enter Name          :  </td> <td> <input type="text" name="txtName">
    <span class="error">* <?php echo $Name_Error;?></span>   </td></tr>

<tr><td> Enter Phone Num     :  </td> <td> <input type="text" name="txtPhone">
     <span class="error">* <?php echo $Phone_Error;?></span>   </td></tr>

<tr><td> Enter Email         :  </td> <td> <input type="text" name="txtMail"> 
      <span class="error">* <?php echo $Mail_Error;?></span>   </td></tr>

<tr><td> Select Gender       :  </td>
<td><input type="radio" name="rdoGender" value="MALE">MALE <br>
<input type="radio" name="rdoGender" value="FEMALE" checked>FEMALE</td></tr>

<tr><td> Enter Address          :  </td> <td> <textarea rows="4" cols="30" name="txtAdd"> </textarea></td></tr>

<tr><td> Select City            :  </td> <td> <select name="sCity" width=40>
<option name="1"> Select
<option name="1"> Canada
<option name="2"> Mumbai
<option name="3"> New York
<option name="3"> Washigton         </td></tr>

<tr> <td colspan=2 align="center"> <input type="submit" name="submit" value="Submit"> </td></tr>
</table>
</form>
</body>
</html>

This code will give following output. Remember this is just HTML and now through PHP, We will apply Validation.
PHP_Form-Validation

Now, we will check whether textbox is empty or not if it is empty then it will give Required message and if it is not empty then check it is alphabets & white spaces or not.

Here we have used one function validate_data() to validate the entered data.

 // Function To Test
     function validate_data($input_data)
     {
          $input_data = trim($input_data);
          $input_data = stripslashes($input_data);
          $input_data = htmlspecialchars($input_data);
          return $input_data;
      }

In that we have used trim() , stripslashes() and htmlspecialchars() function.

  • trim() function trims the white spaces from the beginning and end.
  • stripslashes() removes backslashes from the data.
  • htmlspecialchars() converts special characters into entities of HTML.

One more function has been used in this example i.e. preg_match(). It is used for matching regular expression, returns true if match found else false.

  //Check Validation for Name
         if (empty($_POST["txtName"]))
         {
              $Name_Error = "Name is required";
         }
         else
         {
              $Name = validate_data($_POST["txtName"]);
              if (!preg_match("/^[a-zA-Z ]*$/",$Name))
              {      $Name_Error = "Only letters & White Spaces are allowed";   }
         }

Same code have been applied for phone number and email but with different preg_match expressions.

Lets See Complete Code :

Example :

<html>
<head> <title> PHP FORM Validation</title>
<style>
      .error {color: #FF0000;} // To display Error message in Red Color
</style>
</head>
<body>

<?php
    //Defining Variables and initializing them empty
    $Name_Error= $Phone_Error = $Mail_Error;     
    $Name = $Phone = $email = $Gender = $Address = $City="";                     

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
         //Check Validation for Name
         if (empty($_POST["txtName"]))
         {
              $Name_Error = "Name is required";
         }
         else
         {
              $Name = validate_data($_POST["txtName"]);
              if (!preg_match("/^[a-zA-Z ]*$/",$Name))
              {      $Name_Error = "Only letters & White Spaces are allowed";   }
         }


        //Check Validation for NUmber
        if (empty($_POST["txtPhone"]))
        {
            $Phone_Error = "Phone Number is required";
        }
       else
       {
             $Phone = validate_data($_POST["txtPhone"]);
            if (!preg_match("/^[0-9]/",$Phone))
            {           $Phone_Error = "Only Numbers are allowed";            }
        }
  
     //Check Validation for Email
      if (empty($_POST["txtMail"]))
      {
            $Mail_Error = "Email is required";
      }
     else
     {     $email = validate_data($_POST["txtMail"]);
           if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/",$email))
           {           $Mail_Error = "Invalid Email Id";                      }
     }


    // Other Data to Dispay
    $Gender = $_POST["rdoGender"];
    $Address = $_POST["txtAdd"];
     $City = $_POST["sCity"];
}

     // Function To Test
     function validate_data($input_data)
     {
          $input_data = trim($input_data);
          $input_data = stripslashes($input_data);
          $input_data = htmlspecialchars($input_data);
          return $input_data;
      }
?>

<h2> FORM VALIDATION </h2>
<p><span class="error">* Required field.</span></p>
<form name="frm1"  action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">

<table border=1>
<tr><td> Enter Name          :  </td> <td> <input type="text" name="txtName">
    <span class="error">* <?php echo $Name_Error;?></span>   </td></tr>

<tr><td> Enter Phone Num     :  </td> <td> <input type="text" name="txtPhone">
     <span class="error">* <?php echo $Phone_Error;?></span>   </td></tr>

<tr><td> Enter Email         :  </td> <td> <input type="text" name="txtMail"> 
     <span class="error">* <?php echo $Mail_Error;?></span>   </td></tr>
<tr><td> Select Gender       :  </td>
<td><input type="radio" name="rdoGender" value="MALE">MALE <br>

<input type="radio" name="rdoGender" value="FEMALE" checked>FEMALE</td></tr>
<tr><td> Enter Address          :  </td> <td> <textarea rows="4" cols="30" name="txtAdd"> </textarea></td></tr>

<tr><td> Select City            :  </td> <td> <select name="sCity" width=40>
<option name="1"> Select
<option name="1"> Canada
<option name="2"> Mumbai
<option name="3"> New York
<option name="3"> Washigton         </td></tr>

<tr> <td colspan=2 align="center"> <input type="submit" name="submit" value="Submit"> </td></tr>
</table>
</form>
</body>
</html>

<?php
if (isset($_POST["submit"]))
{
    echo "<table border='1'>";
    echo "<tr><th  colspan='2'> REGISTRATION DETAILS </th></tr>";
    echo "<tr><td>Name :</td><td>$Name</td></tr>";
    echo "<tr><td>Phone :</td><td>$Phone</td></tr>";
    echo "<tr><td>E-mail :</td><td>$email</td></tr>";
    echo "<tr><td>Gender :</td><td>$Gender</td></tr>";
    echo "<tr><td>Address : </td><td>$Address</td></tr>";
    echo "<tr><td>City</td><td>$City</td></tr>";
    echo "</table>";
}
?>

Output :

PHP-Form-Validation

viber image