具有范围属性和一个额外的数字

Having Range attribute and one extra number

我有一个带有 RangeAttribute 的 属性。假设:

[Range(0, 30, ErrorMessageResourceName = "Range", ErrorMessageResourceType = typeof(validationMessages)))]

public int? years {get; set;}

我想要验证范围,但我也想让用户输入另一个数字,比如说 66。反正这里有例外吗?我的意思是,如果用户输入 44,则会显示错误,但如果 he/she 输入 66(仅),he/she 不会出现任何错误?

在这种情况下,您需要定义自己的验证属性。可以直接继承ValidationAttribute class or inherit RangeAttribute,重写几个方法。

class CustomRangeAttribute : RangeAttribute {
    private double special;

    public CustomRangeAttribute(double minimum, double maximum, double special) 
          : base(minimum, maximum) {
        this.special = special;
    }
    public double Special {
        get {
            return this.special;
        }
        set {
            this.special = value;
        }
    }
    public override bool Equals(object obj) {
        CustomRangeAttribute cra = obj as CustomRangeAttribute;
        if (cra == null) {
            return false;
        }
        return this.special.Equals(cra.special) &&  base.Equals(obj);
    }
    public override int GetHashCode() {
         return this.special.GetHashCode() ^ base.GetHashCode();
    }

    public override bool IsValid(object value) {
        return this.special.Equals(value) || base.IsValid(value);
    }
    protected override ValidationResult IsValid(object value,
                       ValidationContext validationContext) {
        if (this.special.Equals(value)) {
            return ValidationResult.Success;
        }
        return base.IsValid(value, validationContext);
    }

}

然后这样使用:

[CustomRange(0, 30, 44, ErrorMessageResourceName = "Range",
     ErrorMessageResourceType = typeof(validationMessages)))]
public int? years { 
    get;
    set;
 }