I\'m using the Data Annotation validation extensively in ASP.NET MVC 2. This new feature has been a huge time saver, as I\'m now able to define both client-side validation
I paired xVal with DataAnnotations and have written my own Action filter that checks any Entity type parameters for validation purposes. So if some field is missing in the postback, this validator will fill ModelState dictionary hence having model invalid.
Prerequisites:
IObjectValidator
interface which declares Validate()
method.ValidateBusinessObjectAttribute
Action filter code:
public void OnActionExecuting(ActionExecutingContext filterContext)
{
IEnumerable> parameters = filterContext.ActionParameters.Where>(p => p.Value.GetType().Equals(this.ObjectType ?? p.Value.GetType()) && p.Value is IObjectValidator);
foreach (KeyValuePair param in parameters)
{
object value;
if ((value = param.Value) != null)
{
IEnumerable errors = ((IObjectValidator)value).Validate();
if (errors.Any())
{
new RulesException(errors).AddModelStateErrors(filterContext.Controller.ViewData.ModelState, param.Key);
}
}
}
}
My controller action is defined like this then:
[ValidateBusinessObject]
public ActionResult Register(User user, Company company, RegistrationData registrationData)
{
if (!this.ModelState.IsValid)
{
return View();
}
...
}