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
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.