static void

ASP MVC Validation

Config

In MVC 3+ it's on by default:

    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

Model

Use Data Annotations (Required, StringLength, RegularExpression, Range). NB: [DataType] is just a UI hint, it won't enforce numbers etc.

View Layout

For client side validation, you need jquery.validate.min.js (github for localizations) and jquery.validate.unobtrusive.min.js. They are already installed (but update in Nuget).

    <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script>

You can't put the Html.BeginForm() and @Html.ValidationSummary() in the _Layout.cshtml.
It needs to be in the page view for unobtrusive validation to work.

Views

@using (Html.BeginForm()) {
    @Html.ValidationSummary()
    @Html.EditorForModel(Model)
    <input type="submit" value="Save"/>
}

Controllers

[HttpPost]
public ActionResult Edit(CategoryModel category)
{
    if (!ModelState.IsValid)
    {
return View("Edit", category); //redisplay
    }
    _repository.Save(category); //save it
    return RedirectToAction("Index");
}

You can add model errors with ModelState.AddModelError(key, string) (fully model-level errors have key: "")

ModelState.AddModelError(key:"", errorMessage:"Invalid");

Custom validators