Contact me See Resume

HTML Form validation using PHP - nareshonline.com

HTML Form validation using PHP

Catagory : PHP and mySQLi Posted : November, 10, 2018
Form validation using PHP

In this tutorial we will make form validation using PHP. We will check and validate to most common element of a HTML form.

Why we need to validation?

HTML form is used to collecting information from user for further communicate or recognizing as well as providing the necessary information to the particular user.

Form Validation Process

Form validation using PHP applies useful security and approach to user for filling the relevant information as per required.

The Process

First we need HTML form with submit button and some input field to collecting data like text, email, text area, radio buttons, checkbox.
For tutorial point of view I am using all most of the form field to make better understand of validation process in PHP.

HTML Form

 <form id="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST">

</form>

Here Im using Id selector for targeting css for the this particular form and its elements and two form attributes :
1. action and 2. method.

The action : $_SERVER[‘PHP_SELF’] perform the validation on current page, for security I will wrap this request into php inbuilt function htmlspecialchars(). htmlspecialchars() function convert the special character like (“”, <>) into HTML entities as &quot;, &gt;, &lt. So hackers can not insert any script or query in our HTML form.

The method : Here I am using post method to sending data to server. The post method is more secure than get method. In get method the request add to the url which is visible to everyone and request remains in browser history which can be cached. This can be harmful for our data.

HTML Structure

<html>
<head>
  <title>HTML form validation using PHP</title>

 
</head>
<body>
<div class="container">

   <form id="contact" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" method="POST">
    <h3>Form Validation</h3>
    <h4>Complete form validation using PHP</h4>
    <fieldset>
      <input placeholder="Your name" type="text" tabindex="1" name="name">
      <span><?php echo $nameErr ;?></span>
    </fieldset>
    <fieldset>
      <input placeholder="Your Email Address" type="email" name="email">
       <span><?php echo $emailErr ;?></span>
    </fieldset>
    <fieldset>
      <input placeholder="Your Phone Number" type="text" name="phone">
      <span><?php echo $phoneErr ;?></span>
    </fieldset>
    <fieldset>
      <input placeholder="Your Pin Code" type="text" name="pin">
      <span><?php echo $pinErr ;?></span>
    </fieldset>
    <fieldset>
      <input placeholder="Your Url" type="text" name="url">
      <span><?php echo $urlErr ;?></span>
    </fieldset>
    <fieldset>
      Gender
      <input type="radio" name="gender[]" value="Male">Male
      <input type="radio" name="gender[]" value="Female">Female
      <br><span><?php echo $genderErr ;?></span>
    </fieldset>

    <fieldset>
      Hobbies
      <input type="checkbox" name="vehicle[]" value="Bike">I have a bike
      <input type="checkbox" name="vehicle[]" value="Car">I have a car
      <input type="checkbox" name="vehicle[]" value="Cycle">I have a Bycycle
      <br><span><?php echo $vehicleErr ;?></span>
    </fieldset>
    <fieldset>
      <textarea placeholder="Type your Message Here...." name="text"></textarea>
      <br><span><?php echo $textErr ;?></span>
    </fieldset>
    <fieldset>
      <button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
    </fieldset>
    <div style="text-align: center;">
    <?php
        $date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
        echo '&copy;'.' Copyright - '. $date->format('d-m-Y');
    ?>
  </div>
  </form>
</div>
</body>
</html>

Styling with CSS

<style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,600);

* {
  margin:0;
  padding:0;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
  -webkit-font-smoothing:antialiased;
  -moz-font-smoothing:antialiased;
  -o-font-smoothing:antialiased;
  font-smoothing:antialiased;
  text-rendering:optimizeLegibility;
}

body {
  font-family:"Open Sans", Helvetica, Arial, sans-serif;
  font-weight:300;
  font-size: 12px;
  line-height:30px;
  color:#777;
  background:#0CF;
}

.container {
  max-width:400px;
  width:100%;
  margin:0 auto;
  position:relative;

}

#contact input[type="text"], #contact input[type="email"], #contact input[type="url"], #contact textarea, #contact button[type="submit"] { font:400 12px/16px "Open Sans", Helvetica, Arial, sans-serif; }

input[type="checkbox"]{
    display:inline-block;
    margin-right:2px;
}
#contact {
  background:#F9F9F9;
  padding:25px;
  margin:20px 0;
  border-radius: 0 30px 0 30px;
}


#contact h3 {
  color: #F96;
  font-size: 40px;
  font-weight: 300;
}

#contact h4 {
  margin:5px 0 15px;
  font-size:13px;
}

fieldset {
  border: medium none !important;
  margin: 0 0 10px;
  min-width: 100%;
  padding: 0;
  width: 100%;
}

#contact input:not([type="radio"]), textarea {
  width:100%;
  border:1px solid #CCC;
  background:#FFF;
  margin:0 0 5px;
  padding:10px;
}
#contact input[type="checkbox"], input[type="radio"]{
  width:auto;
  border:1px solid #CCC;
  background:#FFF;
  margin:0 0 5px;
  padding:10px;
}

#contact input:hover, #contact input[type="email"]:hover, #contact input[type="url"]:hover, #contact textarea:hover {
  -webkit-transition:border-color 0.3s ease-in-out;
  -moz-transition:border-color 0.3s ease-in-out;
  transition:border-color 0.3s ease-in-out;
  border:1px solid #AAA;
}

#contact textarea {
  height:100px;
  max-width:100%;
  resize:none;
}

#contact button[type="submit"] {
  cursor:pointer;
  width:100%;
  border:none;
  background:#0CF;
  color:#FFF;
  margin:0 0 5px;
  padding:10px;
  font-size:15px;
}

#contact button[type="submit"]:hover {
  background:#09C;
  -webkit-transition:background 0.3s ease-in-out;
  -moz-transition:background 0.3s ease-in-out;
  transition:background-color 0.3s ease-in-out;
}

#contact button[type="submit"]:active { box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); }

#contact input:focus, #contact textarea:focus {
  outline:0;
  border:1px solid #999;
}
::-webkit-input-placeholder {
 color:#888;
}
:-moz-placeholder {
 color:#888;
}
::-moz-placeholder {
 color:#888;
}
:-ms-input-placeholder {
 color:#888;
}
    span{
        color:#f00;    
        }
    </style>

Form Validation using PHP

Setting up variable for collecting fields value.

// setting up variables for inputs;
    $name = $email = $phone = $pin = $url = $gender = $vehicle = $text = "";

Setting up variable for collecting if any errors in particular field.

// setting up variables for showing erros
    $nameErr = $emailErr = $phoneErr = $pinErr = $urlErr = $genderErr = $vehicleErr = $textErr = "";

Now we create a function to check input fields.

function test($data)
    {
        $data = trim($data);  // removes the extra spaces, tabs and lines from the input field
        $data = stripslashes($data); // removes the backslaces  (\) from the input field
        $data = htmlspecialchars($data); // converts the special characters into HTML entities 
        return $data;
    }

Now we can perform our verification on submitting the submit button.

// submit button
    if(isset($_POST['submit']))
    {
       // validation for name field
       if(empty($_POST['name']))
       {
            $nameErr = "Name is Required";
       }else
       {
        $name = test($_POST['name']);
        //check if name only contains letters and whitespace
           if(!preg_match("/^[a-z A-Z ]*$/", $name))
           {
               $nameErr = "Only letters allowed with White Space in between";
           }
       }
       // validation for email field
       if(empty($_POST['email']))
       {
            $emailErr = "Email is Required";
       }else
       {
            $email = test($_POST["email"]);
            // check if e-mail address is well-formed
           if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
           {
                $emailErr = "Invalid email format";
           }
       }
       // validation for phone field
       if(empty($_POST['phone']))
       {
            $phoneErr = "Phone is Required";
       }else
       {
            $phone = test($_POST['phone']);
            //check if phone only contains numbers
               if(!preg_match("/^[0-9]*$/", $phone))
               {
                   $phoneErr = "Only numbers allowed";
               }
                else
                {
                    if(strlen($phone)<10)  
                    {
                        $phoneErr = "Invalid Phone";
                    }
                }
       }
       
       // validation for pin field
       if(empty($_POST['pin']))
       {
            $pinErr = "Pin is Required";
       }else
       {
            $pin = test($_POST['pin']);
            //check if phone only contains numbers
               if(!preg_match("/^[0-9]*$/", $pin))
               {
                   $pinErr = "Only numbers allowed";
               }
                else
                {
                    if(strlen($pin)!==6)  
                    {
                        $pinErr = "Invalid Pin";
                    }
                }
       }
       // url verification
       if (empty($_POST["url"]))
       {
            $urlErr = "URL is Required";
        } 
        else 
        {
            $url = test($_POST["url"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
            if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$url)) 
            {
                $urlErr = "Invalid URL";
            }
        }
        // radio button verification
        if (isset($_POST['gender'])) 
        {
            if (!empty($_POST['gender'])) 
            {
              $gender = $_POST['gender'];            }
        } 
        else
        {
            $genderErr = "please select Gender";
        }
        // select button verification
        if (isset($_POST['vehicle'])) 
        {
            if (!empty($_POST['vehicle'])) 
            {
              $vehicle = $_POST['vehicle'];
            }
        } 
        else
        {
            $vehicleErr = "please select Vehicle";
        }
        // validation for text Area
       if(empty($_POST['text']))
       {
            $textErr = "Please submit your comments";
       }else
       {
        $text = test($_POST['text']);
       }
    } // end of submit button

If do not any  errors by submitting form then we can mail or insert data in our database.

I hope it will help you in your projects form validation.

Leave a Reply

You have to agree to the comment policy.