PHP – Form Validation

By | October 2, 2021
PHP - Form Validation

In forms, some of the fields are important and it is necessary that we validate it those fields are filled or not. PHP supports two types of validation:

  • Client-side validation– validation is done on the client-side web browser.
  • Server-side validation– after the submission of the data, the data is sent to the server where it is being validated on the server-side.

How to validate the URL

$website = input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
   $websiteErr = "Invalid URL"; 

How to validate the Email

$db_email = input($_POST["email"]);
if (!filter_var($db_email, FILTER_VALIDATE_EMAIL)) {
   $emailErr = "Invalid email format and please re-enter email"; 


      .error {color: #FF0000;}
         // defining variables and setting them to empty values
         $nameErr = $emailErr = "";
         $name = $email = "";
            if (empty($_POST["name"])) {
               $nameErr = "Name is required";
            }else {
               $name = test_input($_POST["name"]);
            if (empty($_POST["email"])) {
               $emailErr = "Email is required";
            }else {
               $email = test_input($_POST["email"]);               
               // check if e-mail address is in correct format
               if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  $emailErr = "Invalid email format"; 
function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
      <h2>Classes Registration</h2>
     <p><span class = "error">* enter required field.</span></p>
     <form method = "post" action = "<?php 
         echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
               <td><input type = "text" name = "name">
                  <span class = "error">* <?php echo $nameErr;?></span>
               <td>E-mail: </td>
               <td><input type = "text" name = "email">
                  <span class = "error">* <?php echo $emailErr;?></span>
               <input type = "submit" name = "submit" value = "Submit"> 
         echo "<h2>Your values are:</h2>";
         echo $name;
         echo "<br>";
         echo $email;
         echo "<br>";

OutputClasses Registration

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *