Souvik Banerjee
Souvik Banerjee

Reputation: 197

onfocusout on some specific fields using jQuery Validate

I am using jQuery Validate plugin to validate my form. I have a pair of origin and destination city and a pair of start and end date in my form. I want the onfocusout function to work only on airport fields when they have same code in both.

My code below...

$(function () {
    var validator = $("#testForm").validate({
        errorClass: "errorMsg",
        errorElement: "span",
        rules: {
            fromAirport: {
                "required": true,
                "onfocusout": true
            },
            toAirport: {
                "required": true,
                "onfocusout": true
            },
            fromDate: {
                "required": true,
                "onfocusout": false
            }
            toDate: {
                "required": true,
                "onfocusout": false
            }
        },
        messages: {
            fromAirport: {
                "required": "fromAirportis required!"
            },
            toAirport: {
                "required": "toAirportis required!"
            }
            fromDate: {
                "required": "fromDateis required!"
            },
            toDate: {
                "required": "toDate is required!"
            },
        },
        onfocusout: function(el) {
            if (!this.checkable(el)){
                this.element(el);
            }
        },
        submitHandler: function (form) {
        }
    });
});

jsFiddle: https://jsfiddle.net/4yegctz5/1/

Upvotes: 1

Views: 3706

Answers (1)

Sparky
Sparky

Reputation: 98728

  1. Regarding this code...

    onfocusout: function(el) {
        if (!this.checkable(el)){
            this.element(el);
        }
    },
    

What is checkable? There is no such thing represented in this plugin.

  1. Regarding this code...

    rules: {
        fromAirport: {
            "required": true,
            "onfocusout": true // <- No such rule
        }, ...
    

"onfocusout" is not a rule. It's only a callback function that's triggered by an "event" within the form. Additionally, although you can create any custom rule, you cannot create a custom rule that affects the validation events.


OP's Title: "onfocusout on some specific fields using jQuery Validate"

Your only solution would be to over-ride the onfocusout function as follows. I simply placed an arbitrary class on any field that you want to be evaluated on the onfocusout event. Then the custom onfocusout function uses a conditional to check the element for this class and then trigger validation.

onfocusout: function(element) {
    if ($(element).hasClass('ofo')) {
        this.element(element);
    }
},

DEMO: https://jsfiddle.net/4yegctz5/3/

Upvotes: 3

Related Questions