Range annotation between nothing and 100?

怎甘沉沦 提交于 2019-12-01 14:40:02

问题


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

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

My webpage looks like this:

<%=Html.TextBoxFor(u => u.Group.AvailabilityGoal)%>

It works as it should, I can only enter values between 0 and 100 but I also want the input box to be optional, the user shouldn't get an validation error if the input box is empty. This has nothing to do with the range but because the type is an integer. If the user leaves it empty it should make AvailabilityGoal = 0 but I don't want to force the user to enter a zero.

I tried this but it (obviously) didn't work:

[Range(typeof(int?), null, "100")]

Is it possible to solve this with Data Annotations or in some other way?

Thanks in advance.

Bobby


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/2913281/range-annotation-between-nothing-and-100

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