2

I have an MVC 5 application. I am trying to apply validation using my viewmodel attributes. E.g. my fields are required. But for some reason, errors on empty fields are displayed initially, before the user can enter anything. Could you please explain?

@Html.ValidationSummary(false, "Please fix the errors:", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.FileToUpload, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBox("FileToUpload", "", new { @type = "file", @class = "input-xlarge form-control" })
        @Html.ValidationMessageFor(model => model.FileToUpload, "*", new { @class = "text-danger" })
    </div>
</div>

...

public ActionResult Index()
{
    return View();
}

I use my viewmodel only for validation purposes, so it is not passed to the view.

David Shochet
  • 5,035
  • 11
  • 57
  • 105
  • Possible duplicate of [Html.ValidationSummary(false, "message") is always showing, even on page load](http://stackoverflow.com/questions/4166997/html-validationsummaryfalse-message-is-always-showing-even-on-page-load) – Ric Nov 27 '15 at 16:23

1 Answers1

3

As I have commented one solution is to add the following css:

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

But another way is to check if there are errors in your view then display:

@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
    @Html.ValidationSummary(false, "Please fix the errors:", new { @class = "text-danger" })    
}
Ric
  • 12,855
  • 3
  • 30
  • 36