How to specify a min but no max decimal using the range data annotation attribute?

后端 未结 10 1715
旧时难觅i
旧时难觅i 2021-01-31 01:02

I would like to specify that a decimal field for a price must be >= 0 but I don\'t really want to impose a max value.

Here\'s what I have so far...I\'m not sure what the

相关标签:
10条回答
  • 2021-01-31 01:13

    You can use:

    [Min(0)]
    

    This will impose a required minimum value of 0 (zero), and no maximum value.

    You need DataAnnotationsExtensions to use this.

    0 讨论(0)
  • 2021-01-31 01:13

    I would put decimal.MaxValue.ToString() since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.

    0 讨论(0)
  • 2021-01-31 01:16

    It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

    [Range(typeof(decimal), "0", "79228162514264337593543950335")]
    public decimal Price { get; set; }
    
    0 讨论(0)
  • 2021-01-31 01:22

    How about something like this:

    [Range(0.0, Double.MaxValue, ErrorMessage = "The field {0} must be greater than {1}.")]
    

    That should do what you are looking for and you can avoid using strings.

    0 讨论(0)
  • 2021-01-31 01:22

    [Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]

    0 讨论(0)
  • 2021-01-31 01:23

    You can use custom validation:

        [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
        public int IntValue { get; set; }
    
        [CustomValidation(typeof(ValidationMethods), "ValidateGreaterOrEqualToZero")]
        public decimal DecValue { get; set; }
    

    Validation methods type:

    public class ValidationMethods
    {
        public static ValidationResult ValidateGreaterOrEqualToZero(decimal value, ValidationContext context)
        {
            bool isValid = true;
    
            if (value < decimal.Zero)
            {
                isValid = false;
            }
    
            if (isValid)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(
                    string.Format("The field {0} must be greater than or equal to 0.", context.MemberName),
                    new List<string>() { context.MemberName });
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题