Live Form Validation using PHP and Ajax Tutorial

Introduction

In this tutorial, I will show you how to Create Live Form Validation using PHP and Ajax. You will learn the effective way of validating the input field value of a certain form in your web application. The tutorial aims to provide the students and new programmers a reference for learning and enhancing their programming capabilities using PHP Language and jQuery Library. Here, snippets and sample source code will be provided to have a better understanding of the scripts.

What is Form Validation?

Form Validation is a process and one of the important features of the web application for handling and preventing human errors in submitting Form Data. It validates the end-users entered values to each text field whether it is acceptable. With this, the system can prevent invalid data from saving it into the database.

How to Create Live Form Validation using PHP and Ajax?

Live Form Validation can be achieved with the help of jQuery's Ajax API. Using Ajax, we can validate the input field data by sending a request to a PHP Script. Then, the PHP script contains some logic for checking the values entered by the end-user and returning the validation confirmation back to the client side.

Example

Here's an example web application that demonstrates a Live Form Validation using PHP and Ajax. The application is a simple registration. The system validates the input field data each time the end-user inputs, make changes, or focuses out the input field.

The application uses Bootstrap CDN for the page design. Make sure to connect your local-machine to the internet during your testing.

MySQL Schema

  1. CREATE TABLE `members` (
  2. `first_name` varchar(250) NOT NULL,
  3. `middle_name` varchar(250) NOT NULL,
  4. `last_name` varchar(250) NOT NULL,
  5. `email` varchar(250) NOT NULL,
  6. `contact` varchar(50) NOT NULL

Database Connection

db-connect.php

  1. <?php
  2. $host = "localhost";
  3. $username = "root";
  4. $pw = "";
  5. $db_name = "dummy_db";
  6.  
  7. $conn = new mysqli($host, $username, $pw, $db_name);
  8.  
  9. if(!$conn){
  10. die("Database Connection Failed");
  11. }

Interface

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Live Form Validation</title>
  7. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  8. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  9. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  10. html, body{
  11. min-height:100%;
  12. width:100%;
  13. }
  14. .msg-field:empty{
  15. display:none;
  16. }
  17. .input-loader {
  18. position: relative;
  19. right: 0.5em;
  20. top: -1.5em;
  21. }
  22. .spinner-border {
  23. --bs-spinner-width: 0.8rem;
  24. --bs-spinner-height: .8rem;
  25. --bs-spinner-border-width: 0.15em;
  26. }
  27. </style>
  28. </head>
  29. <body class="bg-dark bg-opacity-50">
  30. <nav class="navbar navbar-expand-lg navbar-dark bg-warning bg-gradient">
  31. <div class="container">
  32. <a class="navbar-brand" href="./">Live Form Validation using PHP and Ajax</a>
  33. <div>
  34. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  35. </div>
  36. </div>
  37. </nav>
  38. <div class="container-fluid px-5 my-3 pt-5">
  39. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  40. <div class="card rounded-0 shadow">
  41. <div class="card-body">
  42. <div class="container-fluid">
  43. <form id="memberForm">
  44. <div class="alert msg-field alert-success mb-3 rounded-0 main_success"></div>
  45. <div class="alert msg-field alert-danger mb-3 rounded-0 main_error"></div>
  46. <div class="mb-3">
  47. <label for="first_name" class="form-label">First Name</label>
  48. <input type="text" class="form-control rounded-0" id="first_name" name="first_name" data-validate="true" autocomplete="off">
  49. <div class="d-flex justify-content-end input-loader d-none">
  50. <div class="spinner-border" role="status">
  51. <span class="visually-hidden">Loading...</span>
  52. </div>
  53. </div>
  54. <div class="alert p-1 msg-field alert-danger rounded-0 mt-2 err_msg"></div>
  55. </div>
  56. <div class="mb-3">
  57. <label for="middle_name" class="form-label">Middle Name</label>
  58. <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" autocomplete="off">
  59. </div>
  60. <div class="mb-3">
  61. <label for="last_name" class="form-label">Last Name</label>
  62. <input type="text" class="form-control rounded-0" id="last_name" name="last_name" data-validate="true" autocomplete="off">
  63. <div class="d-flex justify-content-end input-loader d-none">
  64. <div class="spinner-border" role="status">
  65. <span class="visually-hidden">Loading...</span>
  66. </div>
  67. </div>
  68. <div class="alert p-1 msg-field alert-danger rounded-0 mt-2 err_msg"></div>
  69. </div>
  70. <div class="mb-3">
  71. <label for="email" class="form-label">Email</label>
  72. <input type="text" class="form-control rounded-0" id="email" name="email" data-validate="true" autocomplete="off">
  73. <div class="d-flex justify-content-end input-loader d-none">
  74. <div class="spinner-border" role="status">
  75. <span class="visually-hidden">Loading...</span>
  76. </div>
  77. </div>
  78. <div class="alert p-1 msg-field alert-danger rounded-0 mt-2 err_msg"></div>
  79. </div>
  80. <div class="mb-3">
  81. <label for="contact" class="form-label">Contact #</label>
  82. <input type="text" class="form-control rounded-0" id="contact" name="contact" data-validate="true" autocomplete="off">
  83. <div class="d-flex justify-content-end input-loader d-none">
  84. <div class="spinner-border" role="status">
  85. <span class="visually-hidden">Loading...</span>
  86. </div>
  87. </div>
  88. <div class="alert p-1 msg-field alert-danger rounded-0 mt-2 err_msg"></div>
  89. </div>
  90. <div class="mb-3 d-grid">
  91. <button id="submit" type="submit" class="btn btn-warning btn-block rounded-pill">Register</button>
  92. </div>
  93. </form>
  94. </div>
  95. </div>
  96. </div>
  97. </div>
  98. </div>
  99. <script src="app.js"></script>
  100. </body>
  101. </html>

JavaScript

app.js

  1. $(document).ready(function(){
  2. // Form Input Validation
  3. $('#memberForm input[data-validate="true"]').on('input change focusout', function(e){
  4. // Form Input Validation Function
  5. validate_field($(this).attr('name'), $(this).val())
  6. })
  7.  
  8. $('#memberForm').submit(function(e){
  9. e.preventDefault()
  10. $('.main_success, .main_error').text('')
  11. $('#memberForm input[data-validate="true"]').trigger('change')
  12. if($('#memberForm').hasClass('was-validated') !== true)
  13. return false;
  14. $("#submit").attr('disabled', true)
  15. $.ajax({
  16. url:"insertData.php",
  17. method: 'POST',
  18. data: $(this).serialize(),
  19. dataType: 'json',
  20. error:err=>{
  21. console.error(err)
  22. $('.main_error').text("An error occured while saving the data");
  23. $("#submit").attr('disabled', false)
  24. },
  25. success: function(resp){
  26. if(resp.status == 'success'){
  27. $('.main_success').text("New member data has been saved successfully.");
  28. $('#memberForm').removeClass('was-validated')
  29. $('#memberForm .is-valid').removeClass('is-valid')
  30. $('#memberForm')[0].reset();
  31. }else if(resp.status == 'failed'){
  32. if(!!resp.error)
  33. $('.main_error').text(resp.error);
  34. else
  35. $('.main_error').text("An error occured while saving the data");
  36. }else{
  37. $('.main_error').text("An error occured while saving the data");
  38. }
  39. $("#submit").attr('disabled', false)
  40. }
  41. })
  42. })
  43. })
  44. function validate_field($field="", $value=""){
  45. $field = $field.trim();
  46. $value = $value.trim();
  47. if($field == "" || $field == null){
  48. console.error("Input Field Validation Failed: Given Field Name is empty.");
  49. return false;
  50. }
  51. // console.log($(`[name="${$field}"]`).siblings('.input-field')[0])
  52. $(`[name="${$field}"]`).siblings('.input-loader').removeClass('d-none')
  53. $(`[name="${$field}"]`).removeClass('is-valid is-invalid')
  54. $("#submit").attr('disabled', true)
  55.  
  56. $.ajax({
  57. url:'validate.php',
  58. method:'POST',
  59. data:{field:$field, value:$value},
  60. dataType:'json',
  61. error: err=>{
  62. console.error(err)
  63. $(`[name="${$field}"]`).addClass('is-invalid')
  64. $(`[name="${$field}"]`).closest('.err_msg').text("An error occurred while validating the data.")
  65. $(`[name="${$field}"]`).closest('.input-field').addClass('d-none')
  66. },
  67. success:function(resp){
  68. if(resp.status == 'success'){
  69. $(`[name="${$field}"]`).addClass('is-valid')
  70. $(`[name="${$field}"]`).siblings('.err_msg').text('');
  71. }else if(resp.status == 'failed'){
  72. $(`[name="${$field}"]`).addClass('is-invalid')
  73. if(!!resp.error)
  74. $(`[name="${$field}"]`).siblings('.err_msg').text(resp.error);
  75. else
  76. $(`[name="${$field}"]`).siblings('.err_msg').text("The given value is invalid.");
  77. }else{
  78. $(`[name="${$field}"]`).addClass('is-invalid')
  79. $(`[name="${$field}"]`).closest('.err_msg').text("The given value is invalid.");
  80. }
  81. $(`[name="${$field}"]`).siblings('.input-loader').addClass('d-none')
  82. check_form_validity()
  83. }
  84. })
  85.  
  86. }
  87.  
  88. function check_form_validity(){
  89. if($('#memberForm .is-invalid').length > 0){
  90. $("#submit").attr('disabled', true)
  91. }else{
  92. $("#submit").attr('disabled', false)
  93. }
  94. $('#memberForm input[data-validate="true"]').each(function(){
  95. if($(this).hasClass('is-invalid'))
  96. return false;
  97. })
  98. if($('#memberForm input[data-validate="true"]').length == $('#memberForm .is-valid').length){
  99. $('#memberForm').addClass('was-validated')
  100. }
  101. }
  102.  
  103.  

Validation API

valdiate.php

  1. <?php
  2. require_once "db-connect.php";
  3. if(!isset($_POST['field']) || !isset($_POST['value'])){
  4. echo json_encode(['status' => 'failed', 'error' => 'Invalid Field Value or Name']);
  5. }
  6.  
  7. $field = $_POST['field'];
  8. $value = $_POST['value'];
  9.  
  10. switch($field){
  11. case 'first_name':
  12. if(empty($value))
  13. $error = "First Name is a required field";
  14. break;
  15. case 'last_name':
  16. if(empty($value))
  17. $error = "Last Name is a required field";
  18. break;
  19. case 'email':
  20. if(empty($value))
  21. $error = "Email is a required field";
  22. elseif(!(preg_match('/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/', $value)))
  23. $error = "Invalid Email";
  24. else{
  25. $check = $conn->query("SELECT id FROM `members` where `email` = '{$value}'")->num_rows;
  26. if($check > 0){
  27. $error = "The email given is already existed on the database.";
  28. }
  29. }
  30. break;
  31. case 'contact':
  32. if(empty($value))
  33. $error = "Contact # is a required field";
  34. elseif(!(preg_match('/^09([0-9]{9})/', $value)))
  35. $error = "Invalid Format. Must start with 09 and must be 11 digit.";
  36. break;
  37. }
  38.  
  39. if(isset($error)){
  40. echo json_encode(['status' => 'failed', 'error' => $error]);
  41. }else{
  42. echo json_encode(['status' => 'success']);
  43. }

Data Insertion API

insertData.js

  1. <?php
  2. require_once("db-connect.php");
  3. // Data
  4. $data = (array) json_decode(file_get_contents("php://input"));
  5.  
  6. // sanitizing data
  7. $first_name = trim(addslashes($conn->real_escape_string($data['first_name'] ?? "")));
  8. $middle_name = trim(addslashes($conn->real_escape_string($data['middle_name'] ?? "")));
  9. $last_name = trim(addslashes($conn->real_escape_string($data['last_name'] ?? "")));
  10. $email = trim(addslashes($conn->real_escape_string($data['email'] ?? "")));
  11. $contact = trim(addslashes($conn->real_escape_string($data['contact'] ?? "")));
  12.  
  13. /**
  14.   * Save Data After the successfull validation
  15.   */
  16. $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`) VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
  17. $insert = $conn->query($sql);
  18. if($insert){
  19. $response = ["status" => 'success'];
  20. }else{
  21. $response = ['status' => 'error', 'errors' => ["error_msg" => "There's an error occurred while saving the data. Error: ".$conn->error]];
  22.  
  23. }
  24.  
  25. // Return Response
  26. echo json_encode($response);

Snapshot

Here's the snapshot of the result of this sample web application.

Live Form Validation - PHP and Ajax

That's it! You can now test the simple Registration Web App and see if it meets our goal for this tutorial which is to Create Live Form Validation or validate the form input fields without leaving the current page. You can also download the source code zip file by clicking the download button located below this article.

That's the end of this tutorial. I hope this Live Form Validation using PHP and Ajax Tutorial will help you with what you are looking for and that you'll find this useful for your future PHP Projects and Web Development.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Comments

Submitted byAnonymous (not verified)on Sat, 07/29/2023 - 00:40

Thank you!

Add new comment