Quality Online Education Since 2009

PHP Server Side Form Validation

After making a HTML form, you have to check form validation, because there is no guarantee that the input given by user is always correct.

PHP can validate form input server side, submitted by the user using HTML forms.

You need to check a few things:

Employee Information Sample HTML Form

The code block below shows a simple HTML form with PHP Server Side Validation.

The HTML Form

First, let’s look at the form below. The purpose of the form is to capture user details (name, number, and email).



<!doctype html>
<meta charset="utf-8">
<title>Employee Information Sample HTML Form</title>


<?php if (isset($errorMsg)) { echo "<p class='message'>" .$errorMsg. "</p>" ;} ?>

<style type="text/css" >
.errorMsg{border:1px solid red; }
.message{color: red; font-weight:bold; }

<form name= "registration" id= "registration" method= "post" action= "" >
<table width= "400" border= "0" align="center" cellpadding= "4" cellspacing= "1">
<td>Employee Name:</td>
<td><input name= "emp_name" type= "text" id="emp_name" value="<?php if(isset($name)){echo $name;} ?>"
 <?php if(isset($code) && $code == 1){echo "class=errorMsg" ;} ?> ></td>
<td>Contact No.: </td>
<td><input name= "emp_number" type= "text" id= "emp_number" value="<?php if(isset($number)){echo $number;} ?>"
<?php if(isset($code) && $code == 2){echo "class=errorMsg" ;}?> ></td>
<td> Personal Email: </td>
<td><input name= "emp_email" type= "text" id= "emp_email" value="<?php if(isset($email)){echo $email; }?>"
<?php if(isset($code) && $code == 3){echo "class=errorMsg" ;}?> ></td>
<td> </td>
<td><input type= "submit" name= "Submit" value= "Submit" ></td>

Capturing and Validating the Form Contents

Let’s look at the PHP required for validating the submitted form. All of this code would be placed towards the top of the page before the HTML for the form:



if($emp_name =="") {
  $errorMsg=  "error : You did not enter a name.";
  $code= "1" ;

elseif($emp_number == "") {
  $errorMsg=  "error : Please enter number.";
  $code= "2";

//check if the number field is numeric
  elseif(is_numeric(trim($emp_number)) == false){
  $errorMsg=  "error : Please enter numeric value.";
  $code= "2";

  $errorMsg=  "error : Number should be ten digits.";
  $code= "2";

//check if email field is empty
elseif($emp_email == ""){
  $errorMsg=  "error : You did not enter a email.";
  $code= "3";
} //check for valid email 
  elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $emp_email)){
  $errorMsg= 'error : You did not enter a valid email.';
  $code= "3";

  echo "Success";
  //final code will execute here.