Is it possible to add an error for input via ModelState.AddModelError(inputId) to have error highlight on UI and to have it to have to behave as like client validation, i.e. when user changes smth in the input error class would be removed.
asked Mar 29, 2012 at 12:30
drunkcamel
9153 gold badges12 silver badges25 bronze badges
-
Yes, that's the way it works by design. If it's not working for you, make sure that the property name you are using actually matches the model property being rendered on the page and that you have included the validation message in the view (that should be required for client-side as well, though).tvanfosson– tvanfosson2012年03月29日 12:40:35 +00:00Commented Mar 29, 2012 at 12:40
1 Answer 1
Model:
public class MyViewModel
{
[Required]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ModelState.AddModelError("foo", "Foo is required");
return View(new MyViewModel());
}
}
View:
@model MyViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<button type="submit">OK</button>
}
Now when the page is rendered, the Foo field will be highlighted red with an error and when the user types something into the field and blurs out, the error will be removed.
answered Mar 29, 2012 at 12:35
Darin Dimitrov
1.0m277 gold badges3.3k silver badges3k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
drunkcamel
I need to it for dynamically generated input. I don't have model suitable for using attributes.
Darin Dimitrov
@drunkcamel, client side validation relies on data annotation attributes. If you don't have suitable attributes you will have to write custom ones and implement the
IClientValidatable interface to indicate the exact client side validation rules that need to be applied. And if there are custom validation rules you will also have to write custom client side adapters and transpose all the custom logic using javascript functions.lang-cs