asp.net-mvc 使用 MVC 和数据注释在客户端添加大于 0 验证器的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7419194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:28:59  来源:igfitidea点击:

What is the best way of adding a greater than 0 validator on the client-side using MVC and data annotation?

asp.net-mvcunobtrusive-validation

提问by jaffa

I'd like to be able to only allow a form to submit if the value in a certain field is greater than 0. I thought maybe the Mvc Range attribute would allow me to enter only 1 value to signify only a greater than test, but no luck there as it insists on Minimum AND Maximum values.

如果某个字段中的值大于 0,我希望能够只允许提交表单。我想也许 Mvc Range 属性允许我只输入 1 个值来表示大于测试,但是没有运气,因为它坚持最小和最大值。

Any ideas how this can be achieved?

任何想法如何实现?

回答by Darin Dimitrov

You can't store a number bigger than what your underlying data type could hold so that fact that the Range attribute requires a max value is a very good thing. Remember that doesn't exist in the real world, so the following should work:

您不能存储大于基础数据类型可以容纳的数字,因此 Range 属性需要最大值的事实是一件非常好的事情。请记住,这在现实世界中不存在,因此以下内容应该有效:

[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public int Value { get; set; }

回答by Phil

I found this answer looking to validate any positive value for a float/double. It turns out these types have a useful constant for 'Epsilon'

我发现这个答案是为了验证浮点/双精度的任何正值。事实证明,这些类型对“Epsilon”有一个有用的常数

Represents the smallest positive System.Double value that is greater than zero.

表示大于零的最小正 System.Double 值。

    [Required]
    [Range(double.Epsilon, double.MaxValue)]
    public double Length { get; set; }

回答by John Lord

You can create your own validator like this:

您可以像这样创建自己的验证器:

    public class RequiredGreaterThanZero : ValidationAttribute
{
    /// <summary>
    /// Designed for dropdowns to ensure that a selection is valid and not the dummy "SELECT" entry
    /// </summary>
    /// <param name="value">The integer value of the selection</param>
    /// <returns>True if value is greater than zero</returns>
    public override bool IsValid(object value)
    {
        // return true if value is a non-null number > 0, otherwise return false
        int i;
        return value != null && int.TryParse(value.ToString(), out i) && i > 0;
    }
}

Then include that file in your model and use it as an attribute like this:

然后将该文件包含在您的模型中,并将其用作这样的属性:

    [RequiredGreaterThanZero]
    [DisplayName("Driver")]
    public int DriverID { get; set; }

I commonly use this on dropdown validation.

我通常在下拉验证中使用它。