xVal 1.0 and jQuery Validation with ASP.NET MVC 2

Blogging some of the examples from my SouthWest Florida Code Camp session called What's New in ASP.NET MVC 2. Will talk about a few of these at the Tampa Code Camp as well.

 

Client-Side Validation in ASP.NET MVC 2

Earlier I wrote a post on the new Client-Side Validation using jQuery Validation in ASP.NET MVC 2. Let me say that I absolutely love the ease and elegance on how you can simply add a couple of javascript files along with a simple Html.ClientValidationEnabled = true to emit jQuery Validation javascript into your view. Even more important is that the jQuery Validation Rules come from the DataAnnotation Validation Rules that you can decorate on your view model or business classes. This is perfect in that it avoids the duplication and sychronization required to manage the server-side and client-side validation rules you need for your input.

However, this isn't new for us ASP.NET MVC Developers. We also have an open-source implementation, called xVal, that does the same thing and was here before ASP.NET MVC 2 Preview 2. xVal already does what Client-Side Validation does in ASP.NET MVC 2 and works in both version 1 and version 2 of the ASP.NET MVC Framework. It also has another special gift: Remote Validation! This allows you to add validation rules on the client-side that call controller actions on the server via Ajax for validation that needs to be executed on the server in the background. Brilliant!

Because I am so impressed with xVal, I also talked about it at the SouthWest Florida Code Camp in addition to Client-Side Validation introduced in ASP.NET MVC 2 Preview 2. [ See ASP.NET MVC 2 Tutorials for index of tutorials. ]

 

Using xVal with ASP.NET MVC 2

A lot of the code here is taken directly from the post I just wrote on Client-Side Validation using jQuery Validation in ASP.NET MVC 2. Why? Because for the most part there is very little difference between using the two. You decorate your classes with System.ComponentModel.DataAnnotation Validation Attributes and implement the server-side validation in your controller actions the same way. The only difference with xVal is that:

  • You don't need the extra Microsoft JavaScript File MicrosoftMvcJQueryValidation.js
  • You do need the xVal Class Library referenced in your ASP.NET MVC Web Application
  • You use a different Html Helper in the xVal Library to emit the jQuery Validation Code on the View: Html.ClientSideValidation
  • You can take advantage of Remote Validation!

 

Here is our Contact Class with the validation attributes and the simple code you can add to your controller action to perform server-side validation. Nothing has changed from the previous article:

 

 

public class Contact

{

    [Required(ErrorMessage = "Name is required.")]

    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]

    public string Name { get; set; }

 

    [Required(ErrorMessage = "Email is required.")]

    [StringLength(200, ErrorMessage = "Email must be 200 characters or less.")]

    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Valid Email Address is required.")]

    public string Email { get; set; }

}

 

The DefaultModelBinder will handle the validation on the server-side for you so that all you need to do is write code similar to the following to return the errors if they exist:

 

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(Contact contact)

{

    if (!ModelState.IsValid)

        return View(contact);

 

    // ...

}

 

Emitting jQuery Validation to View

Assuming you have referenced the xVal Library in your ASP.NET MVC Web Application, you will have access to an extension method on HtmlHelper, called ClientSideValidation. At a minimum give it the model being validated and it will read the validation attributes on the class and emit the property jQuery Validation code in your view:

 

xVal and ASP.NET MVC 2

 

 

xVal Remote Validation Rules

Notice in the image above: .AddRule(”Email”, new RemoteRule(Url.Action(”EmailInUse”))). This is a remote validation rule that specifies we want to validate the email property on Contact via a Controller Action, called EmailInUse. This allows us to provide real-time client-side validation that let's the user know whether the email address provided is already in use and to pick another.

The EmailInUse Controller Action looks as follows:

 

public RemoteValidationResult EmailInUse(Contact contact)

{

    bool emailInUse = Contact.EmailAlreadyInUse(contact.Email);

    return emailInUse

               ? RemoteValidationResult.Failure("Email already in use")

               : RemoteValidationResult.Success;

}

 

The example above is using ActiveRecord and just checks the database to see if the email address entered already exists and returns the proper RemoteValidationResult.

Slick!!!!

 

Conclusion

At a minimum you have two options for client-side validation with ASP.NET MVC 2 - xVal and the built-in client-side validation. You choose!

Check out my other ASP.NET MVC 2 Tutorials. Come check out the Tampa ASP.NET MVC Developer Group as well where we focus on the ASP.NET MVC Framework!!!!

Hope this helps.

 

David Hayden

 

posted on Saturday, October 10, 2009 3:06 PM

Main

David Hayden Google +

David Hayden Twitter

Health & Fitness

JavaScript Patterns Book Review

HTML 5 and CSS3 - Develop with Tomorrow's Standards Today

Professional ASP.NET Design Patterns Book Review

Beginning Mac Programming Book Review

C# in Depth Book Review

ASP.NET MVC

Orchard CMS

Categories