具有范围属性和一个额外的数字 [英] Having Range attribute and one extra number

查看:97
本文介绍了具有范围属性和一个额外的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有RangeAttribute ..的属性。

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

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

public int? years {get; set;}

我想拥有验证范围,但我也想让用户输入一个数字也可以说66。反正这里有例外吗?我的意思是,如果用户输入44,则会显示错误,但如果他(或她)输入66(仅),他/她将不会收到任何错误?

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?

推荐答案

在这种情况下,您需要定义自己的验证属性。您可以直接从 ValidationAttribute继承类或继承 RangeAttribute

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

这篇关于具有范围属性和一个额外的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆