How to add Form Validation on registration

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 registration 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.

Form validation steps

  • Registration table for store data.
  • Database connection file.
  • index.php file including validation.
  • ajax_request.php for handling dynamic part in our example we check if email already exists or not.
  • Form submission part 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;
}
?>

Now, let’s start with implementation. we use third party library for jQuery and Bootstrap css.

remote: used for call ajax request. in our example ajax_request.php file we use for checking if user entered email is exists or not. so basically restrict with duplication.

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>

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);
}
?>

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!";
    }
}

?>


Conclusion

We are created registration form and implement JS validation using jQuery library. So, it will not store empty data when hit submit button. another request is ajax for email checker when email is exists in Database or not.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply