views:

111

answers:

4

In the code from this answer:

$.validator.addMethod('lessThanEqual', function(value, element, param) {
    return this.optional(element) || parseInt(value) <= parseInt($(param).val());
}, "The value {0} must be less than {1}");

What is the meaning of {0} and {1}? What is the rule of thumb in Javascript to define those parameter replacements?

So based on the comments, I want to further ask in order to pass {0} and {1} here.

What is the syntax I have to use for validation function lessThanEqual.

thank you

+7  A: 

There isn't a "special" meaning, they're just tokens that the validator plugin replaces when displaying the message, numerically referring to the parameters for the rule.

Specifically, this is happening in the plugin:

message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);

So {0} refers to the first parameter, {1} the second and so on. Here's that format function as it is in jQuery.validate 1.7:

$.validator.format = function(source, params) {
  if ( arguments.length == 1 ) 
    return function() {
      var args = $.makeArray(arguments);
      args.unshift(source);
      return $.validator.format.apply( this, args );
    };
  if ( arguments.length > 2 && params.constructor != Array  ) {
    params = $.makeArray(arguments).slice(1);
  }
  if ( params.constructor != Array ) {
    params = [ params ];
  }
  $.each(params, function(i, n) {
    source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
  });
  return source;
};
Nick Craver
+1  A: 

I think it's validator plugin specific templating syntax to bind {0} to the real value and {1} to the "desired" value.

meder
+1  A: 

They are placeholders. In the code that uses the validator, {0} and {1} are replaced by actual values.

SimpleCoder
+1  A: 

They have no special meaning, however they are used as format placeholders, for example:

function format(str/*, args*/) {
  var args = Array.prototype.slice.call(arguments, 1);
  return str.replace(/{(\d+)}/g, function (m, i) {
    return args[i];
  });
}

format("{0} {1}!!", "Hello", "world"); // "Hello world!!"
CMS