注释范围在无到 100 之间?

发布于 2024-09-03 01:02:27 字数 499 浏览 5 评论 0原文

我有一个 [Range] 注释,如下所示:

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

我的网页如下所示:

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

它按应有的方式工作,我只能输入 0 到 100 之间的值,但我也希望输入框是可选的,用户不应该得到如果输入框为空,则会出现验证错误。这与范围无关,而是因为类型是整数。如果用户将其留空,则应使 AvailabilityGoal = 0,但我不想强迫用户输入零。

我尝试了这个,但它(显然)不起作用:

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

是否可以通过数据注释或其他方式解决这个问题?

提前致谢。

鲍比

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

行雁书 2024-09-10 01:02:27

您不必更改 [Range] 属性,因为 [Range] 和其他内置 DataAnnotations 验证器在给定空值时不会执行任何操作。只需将属性本身设置为 int? 类型,而不是 int 类型。不可为 null 的 ValueType 属性(如 int)始终是自动必需的。

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.

好多鱼好多余 2024-09-10 01:02:27

我想您可以覆盖 Range 对象并添加此行为。

public class OptionalRange : RangeAttribute {
    public override bool IsValid(object value) {
        if (value == null || (int)value == 0) return true;
        return base.IsValid(value);
    }
}

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);
    }
}
差↓一点笑了 2024-09-10 01:02:27

这似乎工作得(相当)好:

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

不检查下限。如果你想检查 null || 就不那么方便了>= 0。当然,服务器端验证与客户端验证密切相关,可以检查 this (< 0)。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文