Question

What's the best way to implement field validation using ASP.NET MVC?

I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.

 45  6283  45
1 Jan 1970

Solution

 26

Take a look at the JQuery Validation plugin this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.

Also a sample MVC controller method can be found here which basically uses the JsonResult action type like:

public JsonResult CheckUserName(string username)
{
    return Json(CheckValidUsername(username));
}
2008-08-25

Solution

 6

IMO using xVal with jQuery and DataAnnotationsModelBinder is the best combination.

Sometimes however, there are validation rules which cannot be checked entirely on the client side, so you need to use remote client-side validation.

I figured out way to generically implement remote client-side validation with xVal / jQuery.validate so that

  • Validation rules remain solely in your ASP.NET MVC model
  • You write each validation rule just once, and only in easily testable C# code. There is no JavaScript or other client-side counterpart .
  • There is no need to branch or otherwise modify xVal or jquery.validate
  • All you have to do for each new remote form validation rule is to derive from the base class shown in this article.

I wrote a blog article on this describing all the details.

2009-06-21