Custom Validation Attributes: Comparing two properties in the same model

前端 未结 7 399
谎友^
谎友^ 2020-12-01 06:39

Is there a way to create a custom attribute in ASP.NET Core to validate if one date property is less than other date property in a model using ValidationAttribute<

相关标签:
7条回答
  • 2020-12-01 07:19

    You can create a custom validation attribute for comparison two properties. It's a server side validation:

    public class MyViewModel
    {
        [DateLessThan("End", ErrorMessage = "Not valid")]
        public DateTime Begin { get; set; }
    
        public DateTime End { get; set; }
    }
    
    public class DateLessThanAttribute : ValidationAttribute
    {
        private readonly string _comparisonProperty;
    
        public DateLessThanAttribute(string comparisonProperty)
        {
             _comparisonProperty = comparisonProperty;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ErrorMessage = ErrorMessageString;
            var currentValue = (DateTime)value;
    
            var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
    
            if (property == null)
                throw new ArgumentException("Property with this name not found");
    
            var comparisonValue = (DateTime)property.GetValue(validationContext.ObjectInstance);
    
            if (currentValue > comparisonValue)
                return new ValidationResult(ErrorMessage);
    
            return ValidationResult.Success;
        }
    }
    

    Update: If you need a client side validation for this attribute, you need implement an IClientModelValidator interface:

    public class DateLessThanAttribute : ValidationAttribute, IClientModelValidator
    {
        ...
        public void AddValidation(ClientModelValidationContext context)
        {
            var error = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            context.Attributes.Add("data-val", "true");
            context.Attributes.Add("data-val-error", error);
        }
    }
    

    The AddValidation method will add attributes to your inputs from context.Attributes.

    You can read more here IClientModelValidator

    0 讨论(0)
提交回复
热议问题