Clue Mediator

Form Validation using jQuery in PHP

📅May 16, 2020
🗁PHP

Today we’ll show you how to implement form validation using jQuery in PHP. Moreover we will show you how to insert it into the MySQL database.

There are two types of validations: server side and client side validation. In this article, we will implement client-side validation using jQuery validation plugin. It responds fast to users on input errors before submitting data to the server.

Follow the steps to implement form validation using jQuery

  1. Create a table in database
  2. Include the jQuery library
  3. Create a simple HTML form with jQuery function
  4. Add PHP code
  5. Output

1. Create a table in database

Here, we take an example of a simple registration form and validate the data before insert into the database.

Run the following MySQL syntax to create a table in the database.

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

2. Include the jQuery library

We have to include the below jQuery library in the head section of the page.

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

3. Create a simple HTML form with jQuery function

Now, create a simple form that contains five fields such as name, email, contact, password, confirm password.

Use the following code to create a simple HTML form.

index.php





  <title>Form Validation</title>
  <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">



  <div class="row mt-3">
    <div class="col-md-6">
      <h4 class="mb-3">Form Validation in PHP - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a>
      </h4>
      <form id="form" method="post" action="getData.php">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" name="name" id="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="contact">Contact</label>
          <input type="text" class="form-control" name="contact" id="contact">
        </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>

<style>
  .error {
    color: red;
  }
</style>
<script>
  $(document).ready(function () {
    $('#form').validate({
      rules: {
        name: {
          required: true
        },
        email: {
          required: true,
          email: true
        },
        contact: {
          required: true,
          rangelength: [10, 12],
          number: true
        },
        password: {
          required: true,
          minlength: 8
        },
        confirmPassword: {
          required: true,
          equalTo: "#password"
        }
      },
      messages: {
        name: 'Please enter Name.',
        email: {
          required: 'Please enter Email Address.',
          email: 'Please enter a valid Email Address.',
        },
        contact: {
          required: 'Please enter Contact.',
          rangelength: 'Contact should be 10 digit number.'
        },
        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>

Checkout more articles on In the above jQuery function, we have used two parameters of the jQuery validation plugin.

  • rules - The validation rules that specify which field you want to validate.
  • messages - The error messages which allow you to specify for a particular field and the default message is "This field is required".

This plugin provides the `submitHandler` callback function to handle the submit action when the form is validated.

On successful validation, we will submit post data in `getData.php` file.

4. Add PHP code

Finally we will create a PHP file as `getData.php` to get the posted data and insert it into the database.

In this file, we will write a code to create a database connection and execute the query to insert the data in the table.

getData.php

<!--?php<p-->

  // database connection
  $con = mysqli_connect("localhost", "root", "" , "demo") or die($con);

  // post data
  if(!empty($_POST)) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $contact = $_POST['contact'];
    $password = sha1($_POST['password']);

    // insert data into database
    $sql = "INSERT INTO users (name, email, contact, password) VALUES ('$name', '$email', '$contact','$password')";
    $insertData = mysqli_query($con,$sql);

    if($insertData){
      echo "The form has been successfully submitted.";
    } else {
      echo "Something went wrong!";
    }
  }

?>

After successful submission, you can find the form data into the database table.

5. Output

Run the above code to check the output.

Output - Form Validation using jQuery in PHP - Clue Mediator

Output - Form Validation using jQuery in PHP - Clue Mediator

Refer this article to submit a form without page refresh using Ajax in PHP.

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository