ASP.NET MVC 2 Preview 2: Client-Side Validation
In my opinion one of the most interesting features of ASP.NET MVC 2.0 Preview 2 is the support for client-side validation.
How-to enable Client-Side validation
Client-side validation enable your application to perform client-side validation based on model’s validation by JQuery validation library. Ok, it’s simpler than it sounds.
The client-side validation framework is even extensible, but for now it suits my simple needs.
In my post on ASP.NET MVC 2.0 Preview 1 I’ve added server-side validation to my application model using metadata as ASP.NET Dynamic Data does. So, for example, in the the picture below I’ve added a partial class to my model and a class for metadata describing my requirements for validation. In the following code the attribute ‘Titolo’ must be not null, and I’ve added an Error Message if something’s wrong.
If I run the application all works fine: I show a view page to the user, user enters some value and press Save to submit to server. If the user doesn’t fill the title field he gets an error as soon as we made a POST to server. You can see the page flickering in the browser.
Client-side validation prevent your app going to the server for validation and all happens client side, but using the rules you have defined on the partial class you saw before.
To enable client side validation, you can follow these easy steps:
- use Html.EnableClientValidation method on the View file
- insert three javascript files : jquery-1.3.2.js, jquery.validate.js, MicrosoftMvcJQueryValidation.js. These files are included in the Scripts directory coming with ASP.NET MVC 2 Preview 2 project template.
I’ve put the code in my view page for editing some simple fields.
Now I can run my application and see the results, I’m using HttpWatch to see that no requests are performed to the server and the validation logic works as expected.
As soon as I type something into the textbox the red message disappears.
Nice feature! You can download the ASP.NET MVC 2 Preview 2 from here and read about all the features on Phil Haack post.
Enjoy :-).
Comments
Anonymous
October 03, 2009
awesome! :) what font is used for logo "REMIX"? Thanks a lotAnonymous
October 04, 2009
it should be a big big gif :-)Anonymous
October 07, 2009
Thanks for the post - while obvious once I read it, I was missing the Html.EnableClientValidation call!Anonymous
October 07, 2009
I missed it too the first time :-))))Anonymous
November 03, 2009
The comment has been removedAnonymous
November 05, 2009
Unfortunately is not always possible, this is one of the case..