jQuery server side validation using remote rule

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

While creating a user or getting user input for some data that needs to be validated against the database then you can either use the remote rule or you can define a custom method. In both methods, you need to perform an AJAX call pass user input to the server, and get validation results in response.

In this example, we will use a 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 the jQuery Validate website and download a plugin or get CDNs. Let’s start our example by creating a 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 a simple form with basic information like name, email, and password. Now we will add some validation to this form. We will define remote especially for email. On server side, we will check whether email exists in our database or not. If an email exists 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 the 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 a response. The error message will be displayed based on this response.

Let’s add a sample PHP code to validate the AJAX email parameter and return the result.

<?php
    $email = $_POST['email']);
    $query = "SELECT * FROM users WHERE email = '{$email}' LIMIT 1;"CT * FROM users WHERE email = '{$email}'
    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 jQuery validation and also performed 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.