Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - How to insert a ValidationMessageFor with a line break <br /> at the end?

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.

like image 206
Sleepwalker Avatar asked Dec 23 '11 18:12

Sleepwalker


People also ask

How does Html ValidationMessageFor work?

The Html. ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

How to display Validation error message in MVC?

You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.

What is validation summary in MVC?

The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.


4 Answers

I think what you're actually looking for is:

@Html.ValidationSummary()
like image 57
Phil Klein Avatar answered Sep 28 '22 17:09

Phil Klein


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

like image 41
Bassam Mehanni Avatar answered Sep 28 '22 17:09

Bassam Mehanni


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.

like image 42
Erik Philips Avatar answered Sep 28 '22 16:09

Erik Philips


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

like image 28
rfmodulator Avatar answered Sep 28 '22 15:09

rfmodulator