Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override jquery.validates various validation methods?

I'd like to override the "number" validation of the jquery validate plugin.

This part:

// http://docs.jquery.com/Plugins/Validation/Methods/number
number: function(value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
},

I did some searching but all that I could find was how to override the messages (which I've done already) and how to over ride core jQuery functionality, which pointed me in this direction...

$.fn.validate.prototype.methods.number = function (value, element) {
    return this.optional(element) || /^-?\d+(?:\,\d+)?$/.test(value);
};

With this code I get the following error:

$.fn.validate.prototype.methods is undefined

Am I missing something? Or am I trying to do the impossible?

If this is impossible, suggestions for an alternate way to change this functionality, with out having to add custom validators to every single number field in my app, would be most welcome!

Thanks!

like image 633
Patricia Avatar asked Mar 03 '11 19:03

Patricia


People also ask

How remove validation after field is valid using jQuery?

$("form"). validate(). resetForm();

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

What is remote validation in jQuery?

According to the jQuery validate documentation for remote: The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.


1 Answers

Yes, this functionality is built in to the library, so you can do it without having to deal with the internals.

$.validator.addMethod("number", function(value, element) {
    return this.optional(element) || /^-?\d+(?:\,\d+)?$/.test(value);
});
like image 114
dleavitt Avatar answered Oct 10 '22 05:10

dleavitt