Custom Validation Attributes: Comparing two properties in the same model

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

    As one possible option self-validation:

    You just need to Implement an interface IValidatableObject with the method Validate(), where you can put your validation code.

    public class MyViewModel : IValidatableObject
    {
        [Required]
        public DateTime StartDate { get; set; }
    
        [Required]
        public DateTime EndDate { get; set; } = DateTime.Parse("3000-01-01");
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            int result = DateTime.Compare(StartDate , EndDate);
            if (result < 0)
            {
                yield return new ValidationResult("start date must be less than the end date!", new [] { "ConfirmEmail" });
            }
        }
    }
    

提交回复
热议问题