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
Database Connection
db-connect.php
- <?php
- $host = "localhost";
- $username = "root";
- $pw = "";
- $db_name = "dummy_db";
- $conn = new mysqli($host, $username, $pw, $db_name);
- if(!$conn){
- }
Interface
index.php
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <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>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- .msg-field:empty{
- display:none;
- }
- .input-loader {
- position: relative;
- right: 0.5em;
- top: -1.5em;
- }
- .spinner-border {
- --bs-spinner-width: 0.8rem;
- --bs-spinner-height: .8rem;
- --bs-spinner-border-width: 0.15em;
- }
- </style>
- </head>
- <body class="bg-dark bg-opacity-50">
- <nav class="navbar navbar-expand-lg navbar-dark bg-warning bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3 pt-5">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <div class="card rounded-0 shadow">
- <div class="card-body">
- <div class="container-fluid">
- <form id="memberForm">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="first_name" name="first_name" data-validate="true" autocomplete="off">
- <div class="d-flex justify-content-end input-loader d-none">
- <div class="spinner-border" role="status">
- </div>
- </div>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" autocomplete="off">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="last_name" name="last_name" data-validate="true" autocomplete="off">
- <div class="d-flex justify-content-end input-loader d-none">
- <div class="spinner-border" role="status">
- </div>
- </div>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="email" name="email" data-validate="true" autocomplete="off">
- <div class="d-flex justify-content-end input-loader d-none">
- <div class="spinner-border" role="status">
- </div>
- </div>
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="contact" name="contact" data-validate="true" autocomplete="off">
- <div class="d-flex justify-content-end input-loader d-none">
- <div class="spinner-border" role="status">
- </div>
- </div>
- </div>
- <div class="mb-3 d-grid">
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
JavaScript
app.js
- $(document).ready(function(){
- // Form Input Validation
- $('#memberForm input[data-validate="true"]').on('input change focusout', function(e){
- // Form Input Validation Function
- validate_field($(this).attr('name'), $(this).val())
- })
- $('#memberForm').submit(function(e){
- e.preventDefault()
- $('.main_success, .main_error').text('')
- $('#memberForm input[data-validate="true"]').trigger('change')
- if($('#memberForm').hasClass('was-validated') !== true)
- return false;
- $("#submit").attr('disabled', true)
- $.ajax({
- url:"insertData.php",
- method: 'POST',
- data: $(this).serialize(),
- dataType: 'json',
- error:err=>{
- console.error(err)
- $('.main_error').text("An error occured while saving the data");
- $("#submit").attr('disabled', false)
- },
- success: function(resp){
- if(resp.status == 'success'){
- $('.main_success').text("New member data has been saved successfully.");
- $('#memberForm').removeClass('was-validated')
- $('#memberForm .is-valid').removeClass('is-valid')
- $('#memberForm')[0].reset();
- }else if(resp.status == 'failed'){
- if(!!resp.error)
- $('.main_error').text(resp.error);
- else
- $('.main_error').text("An error occured while saving the data");
- }else{
- $('.main_error').text("An error occured while saving the data");
- }
- $("#submit").attr('disabled', false)
- }
- })
- })
- })
- function validate_field($field="", $value=""){
- $field = $field.trim();
- $value = $value.trim();
- if($field == "" || $field == null){
- console.error("Input Field Validation Failed: Given Field Name is empty.");
- return false;
- }
- // console.log($(`[name="${$field}"]`).siblings('.input-field')[0])
- $(`[name="${$field}"]`).siblings('.input-loader').removeClass('d-none')
- $(`[name="${$field}"]`).removeClass('is-valid is-invalid')
- $("#submit").attr('disabled', true)
- $.ajax({
- url:'validate.php',
- method:'POST',
- data:{field:$field, value:$value},
- dataType:'json',
- error: err=>{
- console.error(err)
- $(`[name="${$field}"]`).addClass('is-invalid')
- $(`[name="${$field}"]`).closest('.err_msg').text("An error occurred while validating the data.")
- $(`[name="${$field}"]`).closest('.input-field').addClass('d-none')
- },
- success:function(resp){
- if(resp.status == 'success'){
- $(`[name="${$field}"]`).addClass('is-valid')
- $(`[name="${$field}"]`).siblings('.err_msg').text('');
- }else if(resp.status == 'failed'){
- $(`[name="${$field}"]`).addClass('is-invalid')
- if(!!resp.error)
- $(`[name="${$field}"]`).siblings('.err_msg').text(resp.error);
- else
- $(`[name="${$field}"]`).siblings('.err_msg').text("The given value is invalid.");
- }else{
- $(`[name="${$field}"]`).addClass('is-invalid')
- $(`[name="${$field}"]`).closest('.err_msg').text("The given value is invalid.");
- }
- $(`[name="${$field}"]`).siblings('.input-loader').addClass('d-none')
- check_form_validity()
- }
- })
- }
- function check_form_validity(){
- if($('#memberForm .is-invalid').length > 0){
- $("#submit").attr('disabled', true)
- }else{
- $("#submit").attr('disabled', false)
- }
- $('#memberForm input[data-validate="true"]').each(function(){
- if($(this).hasClass('is-invalid'))
- return false;
- })
- if($('#memberForm input[data-validate="true"]').length == $('#memberForm .is-valid').length){
- $('#memberForm').addClass('was-validated')
- }
- }
Validation API
valdiate.php
- <?php
- require_once "db-connect.php";
- exit;
- }
- $field = $_POST['field'];
- $value = $_POST['value'];
- switch($field){
- case 'first_name':
- $error = "First Name is a required field";
- break;
- case 'last_name':
- $error = "Last Name is a required field";
- break;
- case 'email':
- $error = "Email is a required field";
- elseif(!(preg_match('/^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,10})$/', $value)))
- $error = "Invalid Email";
- else{
- $check = $conn->query("SELECT id FROM `members` where `email` = '{$value}'")->num_rows;
- if($check > 0){
- $error = "The email given is already existed on the database.";
- }
- }
- break;
- case 'contact':
- $error = "Contact # is a required field";
- $error = "Invalid Format. Must start with 09 and must be 11 digit.";
- break;
- }
- }else{
- }
- exit;
Data Insertion API
insertData.js
- <?php
- require_once("db-connect.php");
- // Data
- // sanitizing data
- /**
- * Save Data After the successfull validation
- */
- $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`) VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
- $insert = $conn->query($sql);
- if($insert){
- $response = ["status" => 'success'];
- }else{
- $response = ['status' => 'error', 'errors' => ["error_msg" => "There's an error occurred while saving the data. Error: ".$conn->error]];
- }
- // Return Response
Snapshot
Here's the snapshot of the result of this sample web application.
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
Add new comment
- Add new comment
- 3401 views