0

I have a jquery validation rule

$.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;
});

On Html, i bind the validation like this

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

When the input is invalid, i always get "Html Error message" as error message, instead of plugin's one "Please insert a valid hex color (#______)"

Jquery validation

How can i get the plugin's error message?

1 Answer 1

1

Not quite sure what you're trying to do here, but you explicitly set the validation message to the value of the data_val_hexcolor here:

options.messages['hexcolor'] = options.message;

The message property of options sent to an adapter contains the value of the data_val_[rulename] attribute.

That's normally what you'd want in ASP.NET MVC, because that allows you to set the validation message from the server, like you do here, rather than in Javascript:

@Html.TextBoxFor( ... data_val_hexcolor = "Html Error message" })

You can ignore the message sent from the server by removing the assignment to options.messages['hexcolor'] entirely, or you could replace that line by:

// Only add view defined message if not empty:
if (options.message)
{
   options.messages['hex_color'] = options.message;
}

... and then set data_val_hexcolor to an empty string in your view (you can't remove the attribute, obviously, because it's the existance of the attribute that triggers the validation rule):

@Html.TextBoxFor( ... data_val_hexcolor = "" })
Sign up to request clarification or add additional context in comments.

1 Comment

Exacly what i needed to know. Thank you

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.