How to validate data from server using jQuery validate

As you know validation is essential part of web application and jQuery validate provides easy implementation of it. Normally jQuery validation is client side validation but you can validate fields using remote rule on your server.

While creating user or getting user input for some data which need to be validate against database then you can either use remote rule or you can define custom method. In both methods, you need to perform AJAX call and pass user input to server and get validation result in response.

In this example, we will use remote rule to perform validation of user email into our database. Here, we will also use bootstrap for some formatting and styling.

Before starting go to jQuery Validate website and download plugin or get CDNs. Let's start our example by creating simple registration form.


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Simple Registration Form</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <style type="text/css">
            .error{
                color:#f00;
            } 
        </style>
    </head>
    <body>
        <div class="container">
            <h2 class="text-center">Register Here</h2>
            <form name="form" id="form" action="/register.php">
                <div class="row">
                    <div class="col-md-8 offset-2">
                        <div class="form-group">
                            <label for="name">Name</label>
                            <input type="text" class="form-control" name="name" placeholder="Enter Name">
                        </div>
                        <div class="form-group">
                            <label for="email">Email</label>
                            <input type="email" class="form-control" name="email" placeholder="Enter Email">
                        </div>
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                        </div>
                        <div class="form-group">
                            <label for="confirm_password">Confirm Password</label>
                            <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm Password">
                        </div>
                        <button type="submit" class="btn btn-primary float-right">Register</button>
                    </div>
                </div>
            </form>
        </div>
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.js" crossorigin="anonymous"></script>
    </body>
</html>

Here, we have created simple form with basic information like name, email and password. Now we will add some validation to this form. We will define remote specially for email. In server side, we will check email exists in our database or not. If email exist in our database then user can not submit form with entered email address. Let's define validation and add PHP code for server side.

Open HTML file and add below code after CDN links.


<script type="text/javascript">
$(document).ready(function() {
    $("#form").validate({
        rules: {
            name: 'required',
            email: {
                required: true,
                email: true,
                maxlength: 255,
                remote :
                {
                    url: 'validateEmail.php',
                    type: "post",
                    data:
                    {
                        email: function()
                        {
                            return $('input[name="email"]').val();
                        }
                    }
                }
            },
            password:{
                required: true,
                minlength: 8,
            },
            confirm_password:{
                required: true,
                minlength: 8,
                equalTo: "#password",
            },
        },
        error: function(label) {
            $(this).addClass("error");
        },
    });
});
</script>

Here, we have called validateEmail.php and passed user input to that AJAX call. On server side, we will validate given email is exist in our database or not and return response. The error message will be displayed based on this response.

Let's add sample PHP code to validate AJAX email parameter and return result.


<?php
    $email = $_POST['email']); 
    $query = "SELECT * FROM users WHERE email = '{$email}' LIMIT 1;";
    $results = $mysqli->query($query);
    if($results->num_rows == 0){
        echo "true";
    }else{
        echo "false";
    }
?>

The PHP code will trigger MySQL query and try to get a single record that has user input in the email field. Then we will check if the result count is 0 or not. If the result is 0 then we will send true otherwise false.

In regular use, a remote rule is used to validate email, numbers, user names, or some complex validation that needs to use data from the back-end. This remote rule will trigger AJAX whenever the email field value is changed. This can impact the performance of the application. You can disable this as per your requirement by setting onkeyup as false.

Conclusion

In this article, we have created a simple registration form and validated it using the jQuery validation and also perform remote or back-end validation for the email field using remote rule and PHP script.

It's a simple example to demonstrate the use of the remote method in the jQuery validate plugin. You can also use a custom method to validate email on the server-side before submitting the form.


Share your thoughts

Ask anything about this examples