I have a [Range] annotation that looks like this:
[Range(0, 100)]
public int AvailabilityGoal { get; set; }
My webpage looks like this:
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);
}
}
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.
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.