1

I'm trying to add custom form validators. And I'm stuck with message customizing issue.

Let's say I want to check if field value does not exceeds max allowed value. I know that 'Validation Plugin' has a "max" validator already - this is just for sample:

$.validator.addMethod("max-numeric", function(value, element, param) {
    var maxValue = $(element).attr("data-max");
    return (!maxValue) || maxValue >= value;
}, $.validator.format('Applicants must be older than {0} and younger than {1} years of age'));

$("#data-form").validate({
    rules: {
        "form.params1.p4":
        {
            "min-numeric": [5, 6]
        }
    }
});

I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format'. And how to pass those parameters?

UPDATE:

Here is the message I get:

Applicants must be older than true and younger than [object HTMLInputElement] years of age

4
  • 1
    The method is called max-numeric, but you're referencing min-numeric in the rules object of the .validate() method. Commented Feb 6, 2016 at 16:55
  • @Sparky This is what happens after 15 hours of non stop coding ). Thank you. Commented Feb 6, 2016 at 16:57
  • I'm not sure if it will make any difference here, but I've found that enclosing the message in $.validator.format() seems to always be totally unnecessary. I've yet to find one instance that breaks when I remove it. Commented Feb 6, 2016 at 17:00
  • @Sparky I just check it - Yes, it works without it. And it looks much better. I guess I'll have to go through docs to find if its eligible Commented Feb 6, 2016 at 17:04

1 Answer 1

2

I cannot comprehend what is responsible for replacing {0} and {1} in '$.validator.format'. And how to pass those parameters?

In your example above, {0} represents the first parameter and {1} represents the second parameter. The parameters are [5, 6] respectively and the automatic replacement of such within the message is handled automatically by the plugin.

So when writing a custom method, there is nothing special you'll need to do. If you pass three parameters into your method...

customMethod: [34, 50, 10]

...then you'll have {0}, {1}, and {2} available for your custom message, representing each value of the parameters respectively.

It just works.


If there is something going wrong, then it's not obvious from your OP aside from:

The method is called max-numeric, but you're referencing min-numeric in the rules object of the .validate() method.

As long as you have two parameters next to max-numeric, then your example would work.

max-numeric: [5, 6]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.