How do I use IValidatableObject?

前端 未结 7 1635
我在风中等你
我在风中等你 2020-11-22 02:59

I understand that IValidatableObject is used to validate an object in a way that lets one compare properties against each other.

I\'d still like to have

7条回答
  •  有刺的猬
    2020-11-22 03:38

    The problem with the accepted answer is that it now depends on the caller for the object to be properly validated. I would either remove the RangeAttribute and do the range validation inside the Validate method or I would create a custom attribute subclassing RangeAttribute that takes the name of the required property as an argument on the constructor.

    For example:

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    class RangeIfTrueAttribute : RangeAttribute
    {
        private readonly string _NameOfBoolProp;
    
        public RangeIfTrueAttribute(string nameOfBoolProp, int min, int max) : base(min, max)
        {
            _NameOfBoolProp = nameOfBoolProp;
        }
    
        public RangeIfTrueAttribute(string nameOfBoolProp, double min, double max) : base(min, max)
        {
            _NameOfBoolProp = nameOfBoolProp;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var property = validationContext.ObjectType.GetProperty(_NameOfBoolProp);
            if (property == null)
                return new ValidationResult($"{_NameOfBoolProp} not found");
    
            var boolVal = property.GetValue(validationContext.ObjectInstance, null);
    
            if (boolVal == null || boolVal.GetType() != typeof(bool))
                return new ValidationResult($"{_NameOfBoolProp} not boolean");
    
            if ((bool)boolVal)
            {
                return base.IsValid(value, validationContext);
            }
            return null;
        }
    }
    

提交回复
热议问题