121

特定のフィールドの値が0より大きい場合にのみ、フォームの送信を許可したいのですが、Mvc Range属性では、テストより大きいことを示すために1つの値しか入力できないと思いましたが、最小値と最大値を要求するため、運がありません。

これをどのように達成できるかについてのアイデアはありますか?

4

4 に答える 4

296
于 2011-09-14T15:57:57.847 に答える
25

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'

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

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

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. Note that because it's extending validationattribute you can customize the error message with a parameter.

于 2019-04-17T20:25:14.530 に答える
0

The above validator works with integers. I extended this to work with a decimal:

    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 に答える