Add custom validation rule in jQuery validate

As we know some jQuery validate provides 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 simple registration form and implement front-end validation using jQuery validate library. Before starting go to official website and download plugin or get CDN. Here, we will also use bootstrap for some designing.

First of all, let's create register 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 form and applied common validation rules like require, min length, email and date. We have also defined 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 year or not. You can modify it as per your requirement.

Let's define logic for our custom method or rule. Add below code before calling 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 above code, we get user entered value into our function and get year difference between date of birth and today. If difference between both dates is greater than 18 years then we allow user to use that date otherwise it will print message to user. Here, at last we have defined custom message as per our example.

Here, we have taken simple example to demonstrate use of custom rule in jQuery validate. The logic for custom function is up to.

Conclusion

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


Share your thoughts

Ask anything about this examples