Html.ValidationSummary(false, "message") is always showing, even on page load
Asked Answered
S

3

47

I am using client side validation and I would like the message below to show only when I have an error. I am trying to use this a general error in case any field is invalid.
Currently

"* denotes required field"

is always showing even before validation.

<%: Html.ValidationSummary(false, "* denotes required field.")%>

I am using model binding to perform validation on client side and MVC.

Surculose answered 12/11, 2010 at 16:46 Comment(0)
G
91

If you use a developer tool in your browser to inspect the validation summary text you'll see that it has the class validation-summary-valid when it is clear but validation-summary-errors when there are form errors.

Therefore, just create a css rule as follows;

.validation-summary-valid {
    display:none;
}

and all should be good.

Georgiegeorgina answered 3/5, 2011 at 19:9 Comment(4)
Why on earth is this not in the default stylesheet?Muskogee
And why on earth does the framework require a single message to summarize both valid and invalid models?Sianna
Well if client-side validation is enabled, they can't remove the div from the page as they would for server-side, as the js needs to be able to show and hide it. They could have just used display:none to hide it, but instead they've used a class which gives you more control over styling (at the cost of making you set up a stylesheet rule either way).Discernible
Thanks for explaining the problem. For some reason this CSS won't work on mobile unless I embed it right in the page, instead of my site-wide CSS file. Instead of doing that, I wrapped the Html.ValidationSummary call in a conditional. I check ViewData.ModelState.IsValid first.Pro
C
4

I think the issue is the fact the Html.ValidationSummary has to appear before the Html.BeginForm otherwise the message is always displayed.

Collaborative answered 24/2, 2011 at 17:51 Comment(4)
But if you do that, you lose the client side checking.Ransome
Moving Html.ValidationSummary above Html.BeginForm made it stop appearing altogether (MVC 4 / Razor).Proximity
Agree - the problem of the summary showing all the time only occurs when ClientValidationEnabled is true. This solution is effectively the same as setting that to false by breaking the client side validation.Discernible
As noted, this just breaks it the other way around.Outleap
T
0

Initially I was checking for a List property on page load so I thought of passing a new model. Then the validation summary just appeared. When I changed my code from

return View(new myModel)

to

return View()

the validation summary did not appear on Get. I also added a null check on the model when checking the property so I can use the latter code.

Theron answered 14/6, 2017 at 4:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.