views:

298

answers:

1

Currently I have a custom attribute that targetted to a class like so:

[PropertiesMustMatch("Password", "PasswordConfirm", ErrorMessage = "Passwords must match!")]

The problem is that in only shows up on the validation summary, and does not highlight the incorrect textboxes. Is there a way to do that?

A: 

Model-level validation means the default Mvc binder doesn't have knowledge of what properties you are validating.

Asp.net Mvc doesn't have built in support for displaying Model-level errors and highlighting properties on the view for that validator.

I might do something like this to achieve the visual result

<%var passwordCssClass = ViewData.ModelState["Key"] != null && ViewData.ModelState["Key"].Errors.Any() ? "model-error" : string.Empty; %>
<%= Html.PasswordFor(x => x.Password, new { @class = passwordCssClass })%>
<%= Html.PasswordFor(x => x.PasswordConfirm, new { @class = passwordCssClass })%>

You've got to inspect the ModelState for the key that the ModelBinder uses for the Model-level validation error. Replace "Key" above with what you find and then the change the css class to w/e your error css class may be.

This is not production level code, you'll want to tweak the Any() and ensure it's the right error message you are looking for and possibly even move the logic for this in the controller and provide the view with the CssClass it should use via your Model. But it should hopefully get you going.

Jab