MVC Validation Lower/Higher than other value

前端 未结 5 1931
北恋
北恋 2020-11-30 00:52

How is the best way to validate a model in MVC.Net where I want to accept a minimum/maximum.

Not individual min/max values for a field. But separate fields for a use

5条回答
  •  误落风尘
    2020-11-30 01:17

    You can use a custom validation attribute here is my example with dates. But you can use it with ints too.

    First, here is the model :

    public DateTime Beggining { get; set; }
    
    [IsDateAfterAttribute("Beggining", true, ErrorMessageResourceType = typeof(LocalizationHelper), ErrorMessageResourceName = "PeriodErrorMessage")]
    public DateTime End { get; set; }
    

    And here is the attribute itself :

    public sealed class IsDateAfterAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string testedPropertyName;
        private readonly bool allowEqualDates;
    
        public IsDateAfterAttribute(string testedPropertyName, bool allowEqualDates = false)
        {
            this.testedPropertyName = testedPropertyName;
            this.allowEqualDates = allowEqualDates;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
            }
    
            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
    
            if (value == null || !(value is DateTime))
            {
                return ValidationResult.Success;
            }
    
            if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
            {
                return ValidationResult.Success;
            }
    
            // Compare values
            if ((DateTime)value >= (DateTime)propertyTestedValue)
            {
                if (this.allowEqualDates && value == propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
                else if ((DateTime)value > (DateTime)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }
    
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessageString,
                ValidationType = "isdateafter"
            };
            rule.ValidationParameters["propertytested"] = this.testedPropertyName;
            rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
            yield return rule;
        }
    

提交回复
热议问题