Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation - Overwriting core validation method

I'm using the jQuery Validation plug-in.

I have overwritten the required rule since mine depends on some custom condition as in following:

$.validator.addMethod("required", function(value, element) {
    console.log("required", element);

    return someCondition && value != null;
}, "This is is required.");

When the form is validated however, I see that "required" is printed twice for each element meaning the function is called twice. As soon as I change the method name to "myRequired" and add the following class rule, the function is called just once as it should be.

$.validator.addClassRules({
    required : {
        myRequired: true
    }
});

It appears that the core required method is still intact and called even if I add a method with the same name. Is there anyway to entirely overwrite the core rule method?

like image 526
Tom Tucker Avatar asked Feb 04 '11 23:02

Tom Tucker


2 Answers

You're not overriding it, but adding another method to it. To override it, try this:

$.validator.methods.required = function(value, element, param) {
    console.log("required", element);

    return someCondition && value != null;
}
like image 169
Herberth Amaral Avatar answered Nov 08 '22 15:11

Herberth Amaral


You can use $.extend to do this:

$.extend($.validator, {
    required: function(value, element) {
        console.log("required", element);
        return someCondition && value != null;
    }
})
like image 1
Rian Schmits Avatar answered Nov 08 '22 15:11

Rian Schmits