Custom Validation Attributes: Comparing two properties in the same model

前端 未结 7 427
谎友^
谎友^ 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:01

    You could compare the two dates in the IsValid() method.

    public class CompareDates : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // get your StartDate and EndDate from model and value
    
            // perform comparison
            if (StartDate < EndDate)
            {
                return new ValidationResult("start date must be less than the end date");
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
    

提交回复
热议问题