121

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

有什么想法可以实现吗?

4

4 回答 4

296
于 2011-09-14T15:57:57.847 回答
25

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

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

    [Required]
    [Range(double.Epsilon, double.MaxValue)]
    public double Length { get; set; }
于 2018-07-20T07:42:05.010 回答
21

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

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

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

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

我通常在下拉验证中使用它。请注意,因为它扩展了验证属性,您可以使用参数自定义错误消息。

于 2019-04-17T20:25:14.530 回答
0

上面的验证器适用于整数。我将其扩展为使用小数:

    public class RequiredDecimalGreaterThanZero : 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
            decimal i;
            return value != null && decimal.TryParse(value.ToString(), out i) && i > 0;
        }
    }
于 2022-03-04T16:26:45.580 回答