3

In the past I have always used the following code to make something globally clear, like with a login form, when the username or the password are not correct. I dont want this error message to link to a specific model property like Username or Password, but just a custom ValidationMessage.

Controller:

ModelState.AddModelError("Combination", "Password or username not correct.");

View:

@Html.ValidationMessage("Combination")

In the new examples that are generated with VS17 it uses not @Html.ValidationMessageFor() and @Html.ValidationMessage() anymore, but the easier
<span asp-validation-for="Username" class="text-danger"></span>

Now the problem occurs that I cannot find anything like asp-validation="Combination" that replaces the @Html.ValidationMessage().

Is it totally different, did I miss something, or do I need to use the old @Html.ValidationMessage() as an alternative?

Max
  • 846
  • 1
  • 9
  • 26

1 Answers1

2

If you want to set a "global" validation error, you can simply use an empty string to specify that the error does not relate to a specific property:

ModelState.AddModelError(string.Empty, "Password or username not correct.");

With this in place, you can use the asp-validation-summary tag-helper to generate your message (or messages - you can call AddModelError multiple times with string.Empty):

<div asp-validation-summary="ModelOnly"></div>

By specifying ModelOnly, only those validation messages you added using string.Empty will be shown.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203