David Shochet
David Shochet

Reputation: 5375

Validation errors are always displayed

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.

Upvotes: 2

Views: 2328

Answers (1)

Ric
Ric

Reputation: 13248

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" })    
}

Upvotes: 3

Related Questions