0
votes

I have a multiple select listbox in an MVC3 form. A user can add & remove custom option elements to and from this listbox. However I want to validate that no 2 options in the listbox contain the same value.

I have created a custom ValidationAttribute that implements IClientValidatable. Both the server and the client validation are working. However, my ErrorMessage looks like this:

ErrorMessage = "{0} has more than 1 '{1}' option.")

Unfortunately I can only pass a partially formatted message to the client validation message, and I do it like so:

var rule = new ModelClientValidationRule
{
    ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
    ValidationType = "noduplicatestringvalues",
};

The validation won't know which option value is duplicated until the validation is run, so I want to complete the message formatting during the validation function.

However, it seems that the error message can only be set during the $.validator.unobtrusive.adapters.add() function.

I have tried setting the data-val-noduplicatestringvalues attribute on the select element during the validation, but the error message is still displayed like so:

FieldName has more than 1 '{1}' item.

Is there any way to change the error message during the validation function?

1

1 Answers

2
votes

You can customize the message.

If you look at the remote validation method in jquery.validate.js, you will see an example of customizing the error message, in that case using a message returned from a remote validation function.