Invalid custom jQuery error messages

I created a custom jquery validation rule that checks for hex color:

$.validator.addMethod("hexcolor", function (value, element) { return this.optional(element) || /^(#){1}([a-fA-F0-9]){6}$/.test(value); }, "Please insert a valid hex color (#______)"); $.validator.unobtrusive.adapters.add("hexcolor", function (options) { options.rules['hexcolor'] = options.params; options.messages['hexcolor'] = options.message; }); 

When I create my text box, I have something like this

 @Html.TextBoxFor(p => p.Color, new { data_val = "true", data_val_hexcolor = "Error message" }) 

I have two problems / questions:

  • If the value is not valid, the error message is "Error message" instead of "Please insert a valid hex color (#_ _ _ _ _ _)"

  • I saw in some other examples the error messages created in this way.

    jQuery.validator.addMethod ("maxWords", function (value, element, params) {return this.optional (element) || stripHtml (value) .match (/ \ b \ w + \ b / g) .length <Titles ;}, jQuery.validator.format ("Enter {0} words or less."));

String placeholder "{0} {1}", etc. are replaced by parameter values?

+4
source share
1 answer

Your question is not very clear to me. However, if you are trying to write your own error messages that take parameters. Here's how to do it:

  jQuery.validator.addMethod('validdate', function (value, element, params) { value = model.date(); if (value === '') { return false; } var range = JSON.parse(params); return value > range[0] && value < range[1]; }, $.format('You can only specify date between {0} and {1}')); 
0
source

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


All Articles