I created my own CompareLessThan validation attribute by copying ASP.NET MVC 3 CompareAttribute and instead of checking for equality, I verify that one property is smaller than the other. If there is an error on the client side, the message "{0} must be less than {1}" is displayed to the user.
My model is configured as follows with Display attributes referencing a resource file.
[CompareLessThan("AmountAvailable", ErrorMessageResourceName="CompareLessThan", ErrorMessageResourceType = typeof(Resources.ValidationMessages))] [Display(Name = "Amount", ResourceType = typeof(Resources.Labels))] public decimal Amount { get; set; } [Display(Name = "AmountAvailable", ResourceType = typeof(Resources.Labels))] public decimal AmountAvailable { get; set; }
Then the GetClientValidationRules spot check method is exactly the same as in CompareAttribute
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationLessThanRule(FormatErrorMessage(metadata.DisplayName), FormatPropertyForClientValidation(OtherProperty), this.AllowEquality); }
Here we create an error message that will be displayed to the user if there is a problem. I can get the display name from the resource file for the property that is decorated with my CompareLessThan custom attribute, but my question is, how can I get the display name of the βotherβ property with which we are comparing? In the IsValid method, we refer to a validationContext from which I can generate a PropertyInfo object for the "other" property, and I think I get the display name. But in GetClientValidationRules I do not have access to this.
I could always just pass a different value for the display name of another property, but I was hoping there would be a way to get it, as I already specify it with data annotations.
Any ideas?
source share