Wednesday, August 17, 2011

Remote (Ajax) Validation in MVC3

Code for sample app
Remote validation is a neat new feature in MVC3 that makes it easy to do AJAX validations. Why would you use these? Any time you don't want to use a full postback but must validate data on the server. How about two basic but common scenarios:
1. Ensuring a registered email address is unique
2. Checking if a login name is in use and in turn Recommending a login name for people to choose - as many systems currently do.

For example, this cheesy app that validates an email address does not equal "test@test.com"




It's quite easy to implement Remote Validation in MVC3. I would recommend getting it working in a small test project first and then migrating to your real project and make sure it works there.

1. I have this working with jQuery 1.4.4 IE ~/Scripts/jquery-1.4.4.min.js
2. Include the [Remote()] attribute on the property on your Model to point to the controller's method to call

        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Please enter a valid e-mail address")]
        [Required()]
        [Display(Name = "Email Address")]
        [Remote("EmailAddressUsed", "Demo", ErrorMessage = "Email Address Already On File")]
        public string EmailAddress { get; set; }

Note here I specify a controller named "Demo" and a method in that controller named EmailAddressUsed. The ErrorMessage attribute above actually didn't work for me, not entirely sure why so I'm returning a message from inside my controller method.

3. The validation fires upon leaving focus (blur) on the form element.
4. Return a Json result from your controller code. Return true if valid, otherwise I'm returning a validation message here.

public JsonResult EmailAddressUsed(string emailAddress)
{
    if (emailAddress == "test@test.com")
    {
        return Json(emailAddress + " is already in use.", JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }
}

That's all there is to it to get up and running: jQuery, controller method, attribute on the model.
Enjoy!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.