JQuery Validator with Parameter

I recently had some work that required me to extend the functionality of the JQuery Validator. The plugin does not have a build in method that will do date comparisons, so I had to create my own.

First resource was to look a thte Jquery documentation. That didn't serve much help because it does not have useful examples that show how the code can be implemented. Eventually I did find a post on Stack Overflow, in the answers section, that gave an idea on how it should work. From that, I was able to roll my own solution to the problem that I had.

Since I had such difficulty finding examples of how to do this, I decided to post the solution that I was able to come up with here so that I and others can use it for future reference.

$.validator.addMethod('dateAfterOrEqualTo',
    function (value, element, params) {
        if (value == '' || params[0].val() == '')
            return true;

        const firstDate = new Date(value), secondDate = new Date(params[0].val());
        return firstDate >= secondDate;
    },
    'Date needs to be after or equal to second date.',
);

The JQuery rule look like this.

// rest of code goes here 

rules: { 
    leadingDate: {
        dateAfterOrEqualTo: [$('#postDate')]
    }
}

// rest of code goes here 

Thus when you run the code above, it will take the value from the field that the rule is being applied to and the value from another field that you choose, convert them both to dates, and then compare them to each other.

From there, you can use your own error message or include one in the addMethod like I have done above.


Last update: 2021-08-12
jquery, web development, javascript, jquery validator
Back to top