5

I'm validating about 10 input fileds in a form. The ValidationMessageFor-tags should be at the top of the page, so I'm writing every one like:

@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)

and so on. My Models look like this:

[Required(ErrorMessage = Constants.ErrorMsgNameMissing)]
public string NAME { get; set; }
[Required(ErrorMessage = Constants.ErrorMsgCityMissing)]
public string CITY { get; set; }

The constants are Strings. Now, if more than one ValidationMessageFor is shown, they are all in one line. How can I insert a line break like <br /> at the end of every message?

This is NOT the right way:

@Html.ValidationMessageFor(model => model.Customer.ADDRESS.NAME)<br />
@Html.ValidationMessageFor(model => model.Customer.ADDRESS.CITY)<br />

since the <br /> is shown even if there is no error...;)

Thanks in advance.

PS: Displaying them as a list would also be great.

Sleepwalker
  • 161
  • 5
  • 12

5 Answers5

3

I think what you're actually looking for is:

@Html.ValidationSummary()
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Phil Klein
  • 7,344
  • 3
  • 30
  • 33
1

I would go with @Html.ValidationSummary() if possible

Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
1

Check out Custom ValidationSummary template Asp.net MVC 3. I think it would be best for your situation if you had complete control over how the validation is rendered. You could easily write an extension method for ValidationMessageFor.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
1

Actually, at the top should be:

@Html.ValidationSummary(/*...*/)

The field validations should be with their respective fields.

However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/) at the top then adjust their layout behavior in your CSS and forget about the <br />'s

rfmodulator
  • 3,638
  • 3
  • 18
  • 22
1

I'm not sure if there's a built in way, but you could easily make another Extension method:

public static MvcHtmlString ValidationMessageLineFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) {
    return helper.ValidationMessageFor(expression) + "<br />";
}

Something like that?

Shlomo
  • 14,102
  • 3
  • 28
  • 43