Introduction
I was recently asked by some students of mine how exactly is client custom validation done in ASP.NET MVC (4). I did this once before unobtrusive validation and jQuery in ASP.NET MVC 2.0 but then I lost contact with the implementation details.
In ASP.NET MVC 4 (this started in MVC 3) there is jQuery unobtrusive validation that works hand-in-hand with Data Annotations (a set of validation attributes that can decorate properties or even (view)model classes). I just remembered that you need to create a ValidationAttribute subclass and also implement IClientValidatable on it. Also you must decorate a property of the (View)Model with this attribute.
On the client side you need to write JavaScript code that provides a validation adapter and a validation function.
Let’s suppose we’d want to create an URL shortening service and on the “Add URL” page we’d have three fields :
– Original URL (textbox)
– Use custom slug (checkbox)
– Custom slug (textbox)
The “Original URL” textbox would be mandatory and the input format should be of a fully-qualified URL (for example “http://blog.andrei.rinea.ro” :P)
The custom slug textbox would be mandatory ONLY if the “Use custom slug” checkbox would be checked. This is the tough part since validating this field requires knowledge of another field’s value (the checkbox in this case). And by tough I mean having to write actual code because there is no out-of-the-box validator for this (not on the server-side nor on the client-side).
This small tutorial will asume that you have knowledge of the ASP.NET MVC platform and C#. I will not go into detail on matters such as what is the MVC pattern, what is the controller, view etc.
Implementation – server side
Let’s start by creating a new ASP.NET MVC 4 web project (select “Internet site” template).
We’ll create a UrlController controller with an action called Add :
using System.Web.Mvc; namespace MVC4_jQuery_Unobtrusive_Custom_Validation.Controllers { public class UrlController : Controller { [HttpGet] public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(AddUrlViewModel userInput) { if (ModelState.IsValid) { // store the data // ... return RedirectToAction("Index", "Home"); } return View(); } } }
Recent Comments