How to add Form Validation in PHP, jQuery.

Form Validation in PHP – Jquery. We are going to implement jquery validation using jquery library with bootstrap UI.
You can use this form as user registeration and front-end designing.
Jquery validation is light weight library and easy to use.

Let’s have create demo file

<!DOCTYPE html>
<html>

<head>
  <title>Form Validation</title>
  <style>
  .error {
     color: red;
  }
  </style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
</head>
 
<body class="container">
  <div class="row mt-3">
    <div class="col-md-6">
      <h4 class="mb-3">Form Validation in HTML - Jquery</h4>
      <form id="form" method="post">
        <div class="form-group">
          <label for="name">First Name</label>
          <input type="text" class="form-control" name="first_name" id="first_name">
        </div>
		
	<div class="form-group">
          <label for="name">Last Name</label>
          <input type="text" class="form-control" name="last_name" id="last_name">
        </div>
		
        <div class="form-group">
          <label for="email">Email Address</label>
          <input type="text" class="form-control" name="email" id="email">
        </div>
        
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" class="form-control" name="password" id="password">
        </div>
        <div class="form-group">
          <label for="confirmPassword">Confirm Password</label>
          <input type="password" class="form-control" name="confirmPassword" id="confirmPassword">
        </div>
        <input type="submit" class="btn btn-primary" value="Submit" />
      </form>
    </div>
  </div>
</body>

<script>
  $(document).ready(function () {
    $('#form').validate({
      rules: {
        first_name: {
			required: true
        },
	last_name: {
	                required: true
        },
        email: {
			required: true,
			email: true
        },
      
        password: {
			required: true,
			minlength: 8
        },
        confirmPassword: {
			required: true,
			equalTo: "#password"
        }
      },
	  
      messages: {
			first_name: 'Please enter First Name.',
			last_name: 'Please enter Last Name.',
			email: {
				required: 'Please enter Email Address.',
				email: 'Please enter a valid Email Address.',
			},
        
			password: {
				required: 'Please enter Password.',
				minlength: 'Password must be at least 8 characters long.',
			},
			confirmPassword: {
				required: 'Please enter Confirm Password.',
				equalTo: 'Confirm Password do not match with Password.',
			}
      },
      submitHandler: function (form) {
			form.submit();
      }
    });
});
</script>
 
</html>


Now let’s move to store data in mysql database. We will create database table call registration and play with it.

  • Create registration table.
  • Create database connection file.
  • Create index.php file including validation.
  • Create ajax_request.php to check if email already exists or not.
  • Create formsubmit.php file to store value.

Let’s create registration table first.

CREATE TABLE registration(
	id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
	first_name varchar(255) NOT NULL,
	last_name varchar(255) NOT NULL,
	email varchar(255) NOT NULL,
	password varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Create Database connection which require to include in file.

config.php

<?php
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);

// Check The Connection
if (mysqli_connect_errno() ){
	echo "Database Connection Failed: " . mysqli_connect_error();
	die;
}
?>

Create index.php, add validation similar like above file but we will also check email exist on database. We will use jquery remote to call ajax file, if email exist on database return true otherwise false.

index.php

<!DOCTYPE html>
<html>

<head>
  <title>Form Validation</title>
  <style>
  .error {
     color: red;
  }
  </style>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
</head>
 
<body class="container">
  <div class="row mt-3">
    <div class="col-md-6">
      <h4 class="mb-3">Form Validation in HTML - Jquery</h4>
      <form id="form" method="post" action="formsubmit.php">
        <div class="form-group">
          <label for="name">First Name</label>
          <input type="text" class="form-control" name="first_name" id="first_name">
        </div>
		
		<div class="form-group">
          <label for="name">Last Name</label>
          <input type="text" class="form-control" name="last_name" id="last_name">
        </div>
		
        <div class="form-group">
          <label for="email">Email Address</label>
          <input type="text" class="form-control" name="email" id="email">
        </div>
        
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" class="form-control" name="password" id="password">
        </div>
        <div class="form-group">
          <label for="confirmPassword">Confirm Password</label>
          <input type="password" class="form-control" name="confirmPassword" id="confirmPassword">
        </div>
        <input type="submit" class="btn btn-primary" value="Submit" />
      </form>
    </div>
  </div>
</body>

<script>
  $(document).ready(function () {
    $('#form').validate({
      rules: {
        first_name: {
			required: true
        },
	last_name: {
			required: true
        },
        email: {
			required: true,
			email: true,
			remote: {
				url  : 'ajax_request.php',
				type: "post",
				dataType:'json',
				dataFilter: function(data) {
					
					var json = JSON.parse(data);
					
					if(json.success == 1) {
						return true;
					}
					return false;
				}
				
			}
        },
      
        password: {
			required: true,
			minlength: 8
        },
        confirmPassword: {
			required: true,
			equalTo: "#password"
        }
      },
	  
      messages: {
			first_name: 'Please enter First Name.',
			last_name: 'Please enter Last Name.',
			email: {
				required: 'Please enter Email Address.',
				email: 'Please enter a valid Email Address.',
				remote: "Email already exists.",
			},
        
			password: {
				required: 'Please enter Password.',
				minlength: 'Password must be at least 8 characters long.',
			},
			confirmPassword: {
				required: 'Please enter Confirm Password.',
				equalTo: 'Confirm Password do not match with Password.',
			}
      },
      submitHandler: function (form) {
			form.submit();
      }
    });
});
</script>
 
</html>

Now, create ajax_request.php file to check if email exists we use JSON. when value is not exist we return success 1 otherwise success 0.

ajax_request.php

<?php
include("config.php");

if(isset($_POST['email'])){
	$query=mysqli_query($connection,"SELECT * FROM registration WHERE email='".$_POST['email']."'");
	$num_row=mysqli_num_rows($query);
	
	$response=array();
	
	if($num_row==0){
		$response=array('success'=>1);
		
	}else{
		$response=array('success'=>0);
	}
	echo json_encode($response);
}
?>

When everything is good. Let’s store value in database.

formsubmit.php

<?php
include("config.php");
// post data
if(!empty($_POST)) {
    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $password = sha1($_POST['password']);
 
    // insert data into database
    $sql = "INSERT INTO registration (first_name, last_name,email,password) VALUES ('$first_name', '$last_name','$email',$password')";
    $success = mysqli_query($connection,$sql);
 
    if($success){
      echo "The form has been successfully submitted.";
    } else {
      echo "Something went wrong!";
    }
}

?>


Leave a Reply