0

I am adding validation for a registration form. Right now, I have this:

<div class="row">
    <div class="alert alert-danger">
        @Html.ValidationMessageFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.EmailAddress)
        @Html.ValidationMessageFor(model => model.Company)
        @Html.ValidationMessageFor(model => model.ClearTextPassword)
    </div>
</div>

The validation works fine, but I have a couple of issues:

  • Right now I have an empty red box when there is no validation that I would very much like to hide. How can I check to see if any validation errors exist for the model as a whole so that I can wrap this in an if statement? e.g. if(model.ValidationErrors.Count > 0)
  • I would also like to wrap this in a ul, how can I check to see if validation was triggered at the property level? e.g. if(model.FirstName.FailedValidation)

Ideally I'd like to perform both of these checks from the view. Thanks!

drewwyatt
  • 5,989
  • 15
  • 60
  • 106
  • why don't you just use a [ValidationSummary](http://stackoverflow.com/questions/8635406/html-validationsummarytrue-whats-the-true-do)? – Liam Jul 07 '14 at 15:32
  • @Liam I don't know what that is. Can you post an answer with an example? – drewwyatt Jul 07 '14 at 15:33

2 Answers2

1

You can add @Html.ValidationSummary() to display the error messages.

Saranga
  • 3,178
  • 1
  • 18
  • 26
1

Why don't you just use a ValidationSummary()?

Basically it does everything you want. Simply replace all of the code in your question with

@Html.ValidationSummary()

You may have to edit some of your CSS as it won't be in exactly the same structure as above.

If you want to produce exactly that structure you will need to play about with the unobtrusive validation javascript (this is non-trivial)

Docs

Liam
  • 27,717
  • 28
  • 128
  • 190