This post is part of the series I’m doing on the newly released ASP.NET MVC 3.
How is it used
I’m going to continue with the example I did in my last post – a simple registration example.
Let’s see what happens if I enable the default client-side validation. To do this, we need to enable the configuration and include the jQuery validation scripts. (You need to put the call to enable client-side validation before the Html.BeginForm call)
You can also enable client-side validation in the Web.config file.
Voila! Let’s take a look at the generated markup.
So the built-in validation attributes will automatically generate the necessary HTML attributes to enable client-side validation. But what happens if we create our own validation attributes? MVC 2 had support for linking your client-side validation scripts to your custom server-side attributes – let’s see how this has changed in MVC 3.
I’m going to create my own attribute to check that a valid e-mail address is entered.
This attribute will take care of the server-side validation, but how do we link it to custom client-side validation? Firstly, we need to create a rule for linking the attribute to the client-side script.
Now we need to link our validation attribute to this rule.
And that’s all we need. The jQuery validation code will automatically trigger our code for properties where our attribute is used.
How to do this in MVC 2
I mentioned that all of this was already possible in MVC 2 – let’s implement the same scenario in MVC 2.
We also need to register this validator on startup.
The client-side validation in MVC 2 suddenly seems very clunky – even without comparing the generated HTML (which is also much simpler in MVC 3).
The fact that we can do away with the validator class is great – the new approach is more intuitive, less error-prone and requires less code. Instead of injecting JSON data into the page we now have custom HTML attributes – much neater.
Brad Wilson did a great post on the different types of validators available in MVC 3. Happy coding.