Using multiple @Html.ValidationMessageFor() helpers with single model property

745 views Asked by At

I'm using @Html.ValidationMessageFor(m => m.Foo) to display unobtrusive validation messages, but when I use it more than once in my View, only one validation message displays.

Here's an example of how I'm using @Html.ValidationMessageFor():

@Html.RadioButtonFor(m => m.Foo, true, new { @id = "FooTrue" })
<label for="FooTrue">Yes</label>
@Html.RadioButtonFor(m => m.Foo, false, new { @id = "FooFalse" })
<label for="FooFalse">No</label>

@Html.ValidationMessageFor(m => m.Foo)

It looks like the <span> elements that @Html.ValidationMessageFor(m => m.Foo) compiles into have fixed id attributes:

<span class="field-validation-error" data-valmsg-for="Foo" data-valmsg-replace="true">
    <span id="Foo-error" class="">
        Please select an option.
    </span>
</span>

Explicitly defining a unique id attribute on my duplicate ValidationMessageFor didn't work:

@Html.ValidationMessageFor(m => m.Foo, "Please select an option", new { @id = "DuplicateValidationMessage" })

Is there any way to use @Html.ValidationMessageFor(m => m.Foo) multiple times in my View?

Also, is a solution possible with Javascript, or will this mess with the jQuery unobtrusive validation plugin?

0

There are 0 answers