How to add custom validation rule in jQuery validate with example

As we know some jQuery validate provides an easy way to implement front-end validation. If you don’t know how to implement jQuery validate then please check How to validate form using jQuery validate.

In this tutorial, we will create a simple registration form and implement front-end validation using the jQuery validate library. Before starting go to the official website and download a plugin or get CDN. Here, we will also use Bootstrap for some designing.

Firstly, let’s create a registration form with some common fields like Name, Email, Phone number, Date of Birth, and password and implement normal validation.

<!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="number">Phone No</label>
                            <input type="number" class="form-control" name="phone" placeholder="Enter Number">
                        </div>
                        <div class="form-group">
                            <label for="date">D.O.B.</label>
                            <input type="date" class="form-control" name="date" >
                        </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>
        <script type="text/javascript">
            $(document).ready(function() {
                //Validation method will define here

                $("#form").validate({
                    rules: {
                        name: 'required',
                        email: {
                            required: true,
                            email: true,
                            maxlength: 255,
                        },
                        phone: {
                            required: true,
                            number: true,
                        },
                        date:{
                            required: true,
                            date: true,
                            validateDOB:true,
                        },
                        password:{
                            required: true,
                            minlength: 8,
                        },
                        confirm_password:{
                            required: true,
                            minlength: 8,
                            equalTo: "#password",
                        },
                    },
                    error: function(label) {
                        $(this).addClass("error");
                    },
                });
            });
        </script>
    </body>
</html>

Here, we have created a form and applied common validation rules like require, min length, email, and date. We have also defined the validateDOB rule but we need to define this validation method on our own.

In this validateDOB method, we will check entered date is older than 18 years or not. You can modify it as per your requirements.

Let’s define logic for our custom method or rule. Add the below code before calling the validate method in your file:

jQuery.validator.addMethod("validateDOB", function(value, element) {

    var today = new Date();
    var dob = new Date(value);
    var age = Math.floor((today-dob) / (365.25 * 24 * 60 * 60 * 1000));

    return age < 18 ? true : false;
},"Sorry, you must be 18 years of age to register");

In the above code, we get user-entered value into our function and get the year difference between the date of birth and today. If the difference between both dates is greater than 18 years then we allow a user to use that date otherwise it will print a message. At last, we have defined custom messages as per our example.

Here, we have taken a simple example to demonstrate the use of custom rules in jQuery validation. The logic for a custom function is up to you.

Conclusion

In this article, we have taken a simple example to validate whether the entered data of birth is older than 18 years or not. You can almost apply any validation or any number of custom rules to your application. You can even use AJAX and validate value with the database too.