Range annotation between nothing and 100?

前端 未结 3 1580
春和景丽
春和景丽 2021-01-17 09:14

I have a [Range] annotation that looks like this:

[Range(0, 100)]
public int AvailabilityGoal { get; set; }

My webpage looks like this:

相关标签:
3条回答
  • 2021-01-17 09:52

    I guess you could override the Range object and add this behaviour.

    public class OptionalRange : RangeAttribute {
        public override bool IsValid(object value) {
            if (value == null || (int)value == 0) return true;
            return base.IsValid(value);
        }
    }
    
    0 讨论(0)
  • 2021-01-17 09:55

    This seems to work as (pretty) well:

    [Range(Double.NaN, 20)]
    public byte? Amount { get; set; }
    

    The lower limit is not checked upon. Not so handy if you want to check null || >= 0. Off course server-side validation goes hand-in-hand with client-side validation where this (< 0) can be checked upon.

    0 讨论(0)
  • 2021-01-17 10:09

    You shouldn't have to change the [Range] attribute, as [Range] and other built-in DataAnnotations validators no-op when given an empty value. Just make the property itself of type int? rather than int. Non-nullable ValueType properties (like int) are always automatically required.

    0 讨论(0)
提交回复
热议问题