17

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?

4
  • 1
    Which validation plugin are you using.
    – Hussein
    Commented Feb 5, 2011 at 0:00
  • I'm using jQuery Validation plugin.
    – Tom Tucker
    Commented Feb 5, 2011 at 0:02
  • Tom, links are always usefull, there many "jQuery Validation" plugins. However i presume you are using this one? bassistance.de/jquery-plugins/jquery-plugin-validation
    – Blowsie
    Commented Feb 14, 2011 at 10:22
  • @Blowsie That's correct.
    – Tom Tucker
    Commented Feb 14, 2011 at 18:42

2 Answers 2

28
+50

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;
}
1

You can use $.extend to do this:

$.extend($.validator, {
    required: function(value, element) {
        console.log("required", element);
        return someCondition && value != null;
    }
})
1
  • Do you have any example or link? Commented Apr 25, 2020 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.