JQuery validation: changing dynamic parameter in message

I have a simple validation method based on an input mask that defines all valid char classes:

<input type="text" required inputmask="254" name="test"/> 

I wrote a function that checks characters of input values ​​for an input mask, and it works great.

Now I want to give the user feedback, so I defined my message:

 $.validator.messages.inputmask = $.validator.format("no, no: input mask is {0}"); 

But I would rather have a function by creating a list of accepted characters based on the mask and use it for feedback, i.e. I want to "manipulate" a parameter:

 $.validator.messages.inputmask = myFunc("hey dude, you are just allowed to use {0}", getChars(dont_know_which_param_to_reference_here); 

This is my JSFiddle: Checking masking of input files (all classes, but accepted in upper case)

As you can see, couples are pleased to check the mask, but cannot be used as user feedback.

Is there any way to do this? Any ideas?

Thanks a lot!

+6
source share
2 answers

Quote OP:

"I want to" manipulate the "parameter"

It is not possible to specifically modify error messages dynamically. However, there is a workaround.

Using the .rules('add') method , you can dynamically rewind messages with new ones.

 // dynamically change message for required rule on input with name="field" $('input[name="field"]').rules('add', { messages: { required: "new message for field 1" } }); 

DEMO : http://jsfiddle.net/F5RUG/

The demo works when the page loads, however you can call .rules('add') whenever you want. If you need to call .rules() more than one field at a time, you must enclose it in jQuery .each() .

DEMO 2 : http://jsfiddle.net/F5RUG/1/

+11
source

You can determine the meaning of your message, as the function and values ​​will be updated every time the check function is called.

In the same way, you can define dynamic values ​​for validation rules.

 var min_items_qt = 0 // Here we dynamically change value of `min_items_qt` $("#yourForm").validate({ rules: { items_qt: { min: function(){ return min_items_qt; } } }, messages: { items_qt: { min: function(){ return "Min items qt. is: " + min_items_qt} } } }); 
+3
source

Source: https://habr.com/ru/post/953039/


All Articles