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

后端 未结 10 1862
旧时难觅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: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() { context.MemberName });
            }
        }
    }
    

提交回复
热议问题