54

I've added validation checks in my controller that modify the ModelState if the validation fails.

For example:

private bool ValidateMoney(string raw, string name, decimal min, decimal max) {
    try {
        var dec = Convert.ToDecimal(raw);

        if (dec < min) {
            throw new ArgumentOutOfRangeException(name + " must be >= " + min);
        }
        else if (dec > max) {
            throw new ArgumentOutOfRangeException(name + " must be <= " + max);
        }
    }
    catch (Exception ex) {
        ModelState.AddModelError(name, ex.GetUserMessage());
    }
    return ModelState.IsValid;
}

However, I never know value to pass for the key parameter in ModelState.AddModelError. (In the example, I just set it to my UI display name.)

What is the parameter for and how should I use it?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
  • 6
    The key argument is not stupid at all, maybe the documentation isn't as clear as it should be. :) – splattne Nov 22 '10 at 09:10

4 Answers4

63

The Key is used by the ValidationMessage HTML Helper to know the exact error message to display.

Example:

<%=Html.TextBox("Name") %> <br />
<%=Html.ValidationMessage("Name") %>

the ValidationMessage helper will display the message that has the key "Name" in the ModelState dictionary.

  • 6
    Validation is used in all sort of applications, not only blogs. –  Jul 14 '09 at 01:39
  • 3
    @Frank respectfully, isn't the feature cool? The Error shows up straight next to the field you want! I learnt this only after google brought me to this question. – gideon Dec 29 '10 at 14:15
  • 6
    the key can be an empty string, but must not be null. If the key is an empty string it can be seen using the Html.ValidationSummary(false) html helper – politus Mar 14 '14 at 17:39
17

The key parameter can be used to associate the validation error with a form field, and thus control where the message appears on-screen. It can be used with both HtmlHelper-type inputs and with simple HTML inputs.

If you've used @Html.TextBoxFor (or similar) and a @Html.ValidationMessageFor, you can get the key's value from the HTML name of the field being validated (use Inspect Element).

If you've just used an HTML <input>, you can add a validation placeholder using @Html.ValidationMessage("AKeyIMadeUp"), and get a message to appear in it like this: ModelState.AddModelError("AKeyIMadeUp", "The value you entered is no good");.

OutstandingBill
  • 2,614
  • 26
  • 38
  • That's what I was wondering; if you're using a helper to generate the field(s), you lose control of the key names, as they're generated by the framework – Tom Lint Jul 24 '20 at 15:08
  • Best answer so far. Got a question tho. Why does the message show up on GET? – SKREFI Dec 14 '20 at 12:24
  • 1
    @SKREFI, not sure I follow. I guess the situation you're talking about is where the page is supported by a GET and a POST in the controller, and normally you'd only expect model validation errors to be present after the POST. But if the view model has attributes such as [Required] (writing on my phone, and can't remember the exact syntax) and it's empty, that might cause the situation you're seeing. Not certain, but that's my first guess. – OutstandingBill Dec 16 '20 at 04:31
  • I see, I think I have done a little mistake in my code, I don't have that problem anymore. I still have troubles with HTML as in, I can't get all the errors and make a switch case on "error", because I have some special classes I have to set for different divs based on the error. Thank you for your reply and explanation! – SKREFI Dec 16 '20 at 10:55
7

Sorry to Necropost. The above answers didn't have this detail that I thought was useful (it was what I was looking for!!)

In order to create 'Model Wide' Validation errors - then you simply add string.Empty as your Key.

e.g.

ModelState.AddModelError(string.Empty, "This is my Model Level Message");

Thanks to : http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary for the tip.

yeti_c
  • 135
  • 2
  • 8
4

Actually you can set any validation message while your form submission unsuccessful suppose you make a field in model

[Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

and while your modelState got invalid you can set error message bind with that field like as.

ModelState.AddModelError("OldPassword", "Current Password do not match ");

then your error message will be bind with field in model named "OldPassword"

mk Mughal
  • 286
  • 4
  • 16