Having Range attribute and one extra number

雨燕双飞 提交于 2019-12-25 06:33:57

问题


I have a property with RangeAttribute.. let's say:

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

public int? years {get; set;}

I want to have the validation range but i also want to let the user enter ONE other number let's say 66 as well. is there anyway to have an exception here? i mean if the user enters 44, the error is shown but if he/she enters 66 (only) he/she does not get any error?


回答1:


You need to define your own validation attribute in that situation. You can directly inherit from ValidationAttribute class or inherit RangeAttribute and override a few methods.

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);
    }

}

And then use that in this way:

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


来源:https://stackoverflow.com/questions/29939996/having-range-attribute-and-one-extra-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!