0

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?

danludwig
  • 46,965
  • 25
  • 159
  • 237

1 Answers1

2

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.

counsellorben
  • 10,924
  • 3
  • 40
  • 38
  • Funny, I read another post from you the other day regarding null FormContext causing data-val attributes not to show up when loading a partial view with form inputs. Thanks will try this... – danludwig Oct 05 '11 at 21:18