ASP.NET MVC 3 Data Annotation: Add validation dynamically

前端 未结 3 1683
北荒
北荒 2021-02-18 22:52

I\'m new with data annotation. I\'d like to know if it possible (and how) to add some validation dynamically. It is very extensive to explain why, but I\'ve a ViewModel that rec

3条回答
  •  死守一世寂寞
    2021-02-18 23:32

    I think that the simplest way of doing what I wanted is implementing IValidatableObject:

    public class Product : IValidatableObject
    {
        public int Prop1 { get; set; }
        public int Prop2 { get; set; }
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            if (Prop1 < Prop2)
                yield return new ValidationResult("Property 1 can't be less than Property 2");
        }
    }
    

    See also: Class-Level Model Validation with ... ASP.NET MVC 3

提交回复
热议问题