4
votes

I created a custom jquery validation rule which 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 textbox, i have something like this

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

I have two problems/questions:

  1. When the value is invalid, the error message is "Error message" instead of "Please insert a valid hex color (#_ _ _ _ _ _)"

  2. I've seen in some other examples error messages created like this.

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

String placeholder "{0} {1}" etc are replaced with the values of the parameters?

1

1 Answers

0
votes

Your question is not very clear to me. However, if you are trying to write custom error messages that accept parameters. This is how to achieve that:

 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}'));