Validation in ASP.NET MVC - part 3: client-side validation with jquery validation
/ 4 min read
This is part 3 of a series of posts. See also:
- Validation in ASP.NET MVC - part 1: basic server-side validation
- Validation in ASP.NET MVC - part 2: custom server-side validation
In the first two parts, I showed how you can perform validation on the server side with Castle Validation attributes and extend that model with custom validation logic. With this, we have everything we need to properly validate our model.
For a better user experience though, it would also be nice that we could re-use (part of) our validation logic on the client-side. Luckily, lots of others have already looked into this and the only thing I had to do was to throw everything together and stir it a little bit :).
The ingredients are:
- The jQuery validation plugin (an obvious choice, since we were already using jQuery in Cuyahoga);
- Monorail client-side code generator for jQuery validation (originally contributed by Gildas, but also many credits to the Castle Monorail guys for creating such a flexible infrastructure);
- Model-based Client-side Validation for ASP.NET MVC (very inspiring blog post by Steve Sanderson).
How it works
- The client-side validation is called via an HtmlHelper extension method ClientSideValidation: <%= Html.ClientSideValidation(ViewData.Model, “my_form_id”)%>;
- The HtmlHelper extension requests an instance of a BrowserValidationEngine that returns the client script for validation;
- BrowserValidationEngine has a reference to an IValidatorRegistry instance that returns all (Castle) validators for the given model;
- For each validator, the referenced IBrowserValidatorProvider generates the appropriate client script;
- Finally, all generated client script code is combined and sent to the browser in a single javascript block.
The existing Monorail codebase proved to be of great value and could be used almost seamlessly. The only difference is the way the client code is generated. Originally, the validators generated css class attributes for the Monorail form helpers, but we don’t have those with ASP.NET MVC, so all client code is generated as jQuery validation rules.
Below, you can see the output of the validation helper for the new user form in Cuyahoga:
which results in this:
Summarizing validation
In this series of posts, I showed how we deal with validation in Cuyahoga and ASP.NET MVC. Personally, I think the nicest part of it is that we have our validation rules centralized and we only have to add one line of code to the view to enable client-side validation.
The code can be found in Cuyahoga SVN and more specifically in the validation sections and the ASP.NET MVC manager. I’ll try to make a standalone sample project with all the validation stuff somewhere in the near future.