自定义数据注解 CompareAttribute

Customize data annotations CompareAttribute

我需要使用 .net data annotations 比较 class 中的两个属性。应填写两个属性之一,另一个应为空白。如何覆盖 CompareAttribute 的行为?如果不可能,替代解决方案是什么?

此 class 适用于一个问题: 如果 属性 A 被设置为某些东西并且 属性 B 已经有一个值,那么 属性 A 将如预期的那样无效。消隐 属性 B 后,属性 A 应该生效,但直到我尝试修改 属性 A 时才会生效,因此我再次触发验证。有没有办法将两者连接在一起以触发对两者的验证?

 class CustomAttribute : ValidationAttribute
        {
        private readonly string _other;
        public CustomAttribute(string other)
            {
            _other = other;
            }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
        var property = validationContext.ObjectType.GetProperty(_other);
        if (property == null)
            {
            return new ValidationResult(
                string.Format("Unknown property: {0}", _other)
            );
            }
        var otherValue = property.GetValue(validationContext.ObjectInstance, null);


        if (!String.IsNullOrEmpty(value.ToString()) && !String.IsNullOrEmpty(otherValue.ToString()))
            {
              return new ValidationResult("Test");
            }
        return null;
        }
    }

对于这样的东西,我使用 ExpressiveAnnotations。它有一个辉煌的RequiredIf属性:

[RequiredIf("B == null", ErrorMessage = "Either A or B should be filled")]
public string A { get; set; }

[RequiredIf("A == null", ErrorMessage = "Either A or B should be filled")]
public string B { get; set; }

您可以使用自己的 class 扩展 CompareAttribute:

public class CustomCompareAttribute: CompareAttribute {
    public CustomCompareAttribute(string otherProperty) : base(otherProperty) {
    }

   protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
       if (OtherProperty == null && value == null) {
            return new ValidationResult("Either A or B should be filled");
        }
        // more checks here ...
   }
}