PDA

Click to See Complete Forum and Search --> : VS 2010 [RESOLVED] [MVC3] Implementing a custom validation attribute for CompareTo


tr333
Jul 13th, 2011, 07:55 PM
The System.Web.Mvc.CompareAttribute checks if two properties in a Model are equal, but I wanted to implement a validation attribute to check if x < y or x > y, instead of just x == y. All the examples I've found so far on Google show how to implement an attribute for class-level validation, but I haven't yet found any examples that show it for property-level validation.

Serge
Jul 28th, 2011, 11:28 AM
Actually ActionFilters CAN work both on the class level as well as on an individual ActionResult. As long as you don't decorate your ActionFilter with definition to ONLY allow it on the class level.


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
Public class CompareTo: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
....your logic goes here for comparing
}
}

tr333
Aug 2nd, 2011, 11:58 PM
I found a guide at http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2 which explains how to implement custom validation attributes for model properties.