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"/>
}
- @Html.ValidationSummary is just like the webforms validation summary.
There's an overload which doesn't show property annotations: @Html.ValidationSummary(excludePropertyErrors:true)Html.ValidationSummary must be inside the form (and NOT in the _Layout) - @Html.EditorForModel(Model) may be useful for simple models
- @Html.EditorFor (or @Html.TextBoxFor etc) render the inputs with data attributes, which the unobtrusive javascript uses
- @Html.ValidationMessageFor is just a placeholder for property validations (may duplicate @Html.ValidationSummary)
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
- Brad Wilson MVC 3 intro
- Data Annotations: write a ValidationAttribute and override IsValid(value, context)
- Also implement IClientValidable GetClientValidationRules(modelMetadata, context).
You return (an enumerable of) ModelClientValidationRule, which has an ErrorMessage (use metadata.GetDisplayName()), ValidationParameters (inputs) and ValidationType (js method name) - Javascript adaptor (one of add, addBool, addSingleValue, addMinMax):
$.validator.unobtrusive.adapters.
addBool("validcreditcard"); - Add the javascript validator:
$.validator.addMethod("validcreditcard",
function (value, element) {
return !isNaN(parseInt(value, 10));
});