Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validation: change dynamic parameter within message

I have a simple check method based on a input mask defining all allowed char classes:

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

I wrote a function checking the input value characters against the inputmask and it works fine.

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

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

But I would prefer to have a function, building the list of accepted characters based on the mask and use this for feedback, i.e. I want to 'manipulate' the parameter:

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

This my JSFiddle: Input Mask Validation (all classes but uppercase accepted)

As you can see the param is nice to check against the mask but can't be used as an user feedback.

Is there any way to do so? Any kind of ideas?

Thanks a lot!

like image 705
John Rumpel Avatar asked Sep 03 '13 08:09

John Rumpel


2 Answers

Quote OP:

"I want to 'manipulate' the parameter"

There is no way to specifically change error messages dynamically. However, there is a workaround.

By using the .rules('add') method, you can dynamically over-ride your 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/

Demo works on page load, however, you can call .rules('add') whenever you wish. If you need to call .rules() on more than one field at a time, you must enclose it within a jQuery .each().

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

like image 58
Sparky Avatar answered Sep 23 '22 13:09

Sparky


You can define your message value, like function and values will be updated each time, when the validate function will be 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}
    }
  }
});
like image 39
Dmitry Avatar answered Sep 24 '22 13:09

Dmitry