Dynamic jQuery Validate error messages with AddMethod based on the element

jquery validate add message dynamically
jquery validate custom error message
jquery validator addmethod params example
jquery validator addmethod multiple elements
jquery validator addmethod for email
validator addmethod regex
jquery validate alphanumeric
jquery validate custom rule

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?

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 to addMethod, the error message is the 3rd argument.

Dynamic error message in Jquery validation – Interesting coding , $.validator.addMethod('min-length', function (val, element) { // do stuff // the error message here needs to be dynamic }, 'The field cannot be less  I am not a champ at asp.net mvc and found myself struggling with a task that at first I thought will be trivial, below is how I got through

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.

Validate: need dynamic message on failed validation, addMethod Example, we want to have a validation name CheckABC to return error message base on element and parameter u pass in. From the documentation, addMethod can take a function as the 3rd (i.e. message) param.See what happens when you pass a function, and inside it console.log(this).There's a good chance that this will be the element you're interested in.

Found this semi by accident. My messages are very dynamic depending on the result. so right before I call validate I add an attribute data-msg="My custom message" to the element. Validator will pick that up:

err_msg = 'My custom message';
$('#my_element_id').attr('data-msg', err_msg);
$('#my_form_id').validate().element('input[name=\'my_element_name\'');

found some code references under customDataMessage in jquery.validate.js

[Validate] Group validation messages dynamic fields, I need to include the contents of a field in a validation error message. I tried using a closure around the addMethod call as demonstrated in the code. element);; if (selectedType.CanLinkToClosedItems) {; msg +=  For some reason, even with a broad class based selector, jQuery Validator only ever seems to select the first element of that type. I spent a long time wondering what was going on, but eventually gave up and did something similar to what @Rick has done in a different answer.

late to the party here, but this seems to work for me:

jQuery.validator.addMethod("minDate", function(value, element, param) {
    var inputDate = new Date(value);
    return (inputDate >= param)
    }, function(param, element) {
        return 'Enter a date greater than or equal to ' + $.datepicker.formatDate("M d, yy", new Date(param));
});

where the minDate value has previously been set on the control to validate something like this:

$('form:first').validate({
    rules: {
        "date-filed": {
            minDate: new Date(2000,0,0)
        },
...

Validation Plugin, changing message with addMethod, I have a form with dynamic fields. I validate them by using a class. So if you leave them empty you get a message "Check from fields" ? 1 addMethod(; "op",​; function(value,element) {; if (value == '') {; return false;; }; return true;; } Assign oneMessage class to all elements in the group and use this. jQuery.validator.addMethod( name, method [, message ] ) Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.

If Barmar's answer doesn't work for you, it is probably because your settings for the element already contains an error message(set from the server in asp.net MVC for example)

So the jQuery.validate code will ignore the new default set by the second parameter to $.validator.addMethod

A way around it is to do the following:

$.validator.addMethod('min-length', function (val, element) {
   this.settings.messages[element.name]['min-length'] = function () { return 'put your custom message here'; };

   return this.optional(element) || val.length >= $(element).data('min');
});

jQuery.validator.addMethod(), Hi, I've written my own custom validation method using addMethod which works great. But what I'd like to do is change the error message depending on addMethod("myvalidator", function(value, element) {; var returnVal  Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

How to Show different error message in jQuery.validator.addMethod , 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  Using a library to do form validation can save lots of your development time. Being a tested and proven library guarantees it. jQuery Form validation library is the most popular validation library. This post collects all my notes and references on jQuery Form validation library.

[PDF] Jquery.validator.addmethod Dynamic Error Message, It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message. ¶jQuery.validator. jQuery.validator.addMethod() Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.

jQuery.validator.addMethod('greaterThan', function (value, element, params) { var thiserror = ""; if (params.isreq == "true" && value.length == 0) 

Comments
  • From the documentation, addMethod can take a function as the 3rd (i.e. message) param. See what happens when you pass a function, and inside it console.log(this). There's a good chance that this will be the element you're interested in. Or, maybe element is passed in as a param, just like it is for the other function you have.
  • Thanks so much Barmar! Had no idea you could do that :) Also you're right it isn't in the closure, my mistake.
  • Just what I was looking for. A tiny step further, you can construct a custom error message inside the validation function, and stash it in the element's data, e.g $(element).data('error','... custom message ...') and then recover it in the message function via return $(element).data('error')
  • One other addition is that if there is a message defined elsewhere, on the ruleset, for example, this 3rd parameter to addMethod will be ignored. I thought the validator would use the parameter first, then use the default if null or an empty string was returned.
  • element isn't a jQuery object. Does it need to be turned into one?
  • @Barmar: what happens to params in the 3rd argument? I tried console.log( params ); and its printing true. Where does this argument comes from?
  • I have upvoted your answer because it does solve the example presented in the question but Barmar's answer gives a more generic solution, which was what I was looking for when I landed in this page.