问题
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