I\'ve added validation checks in my controller that modify the ModelState
if the validation fails.
For example:
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");
.
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"
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.
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.