Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic jQuery Validate error messages with AddMethod based on the element

Let's say I have a custom AddMethod to jQuery Validate like:

$.validator.addMethod('min-length', function (val, element) {     // do stuff  // the error message here needs to be dynamic }, 'The field cannot be less than than '      + element.attr('data-min') + // it is within the closure, but it can't grab it    ' length.'); 

I can't figure out a way to get the element variable in question, and get any values from it. What am I missing here?

like image 647
Mark Pieszak - Trilon.io Avatar asked Nov 12 '12 22:11

Mark Pieszak - Trilon.io


2 Answers

From looking at the validator source code, I think this should do it:

$.validator.addMethod('min-length', function (val, element) {     return this.optional(element) || val.length >= $(element).data('min'); }, function(params, element) {     return 'The field cannot be less than than ' + $(element).data('min') + ' length.'; }); 

In your original code, the message string is NOT within the closure; the closure is the 2nd argument of addMethod, and the error message is the 3rd argument.

like image 123
Barmar Avatar answered Sep 20 '22 17:09

Barmar


First of all, I appreciate Barmar answer.

If you just think , you can use any of the jquery validation message with it's param value , you can call simply the message instances.

Here is the code

            jQuery.validator.addMethod("custom_min", function(value, element, param) {                 value = replaceAll(value, ',' , '');                 return this.optional( element ) || value >= param;             },jQuery.validator.messages.min );   

In jquery validation

jQuery('#form_id').validate({    rules: {     'field_name': {        required: true,        number: true,        custom_min: 1000    } }); 

So if you enter something less than 1000. it will throw you error message,"Please enter value greater than 1000(the amount you put in the validation)".This method will be faster if your validation needs any modification of any current method or you are developing it with multiple language.

like image 27
Rocker Maruf Avatar answered Sep 21 '22 17:09

Rocker Maruf