mvc4 data annotation compare two dates

前端 未结 3 1576
独厮守ぢ
独厮守ぢ 2020-12-04 18:09

I have these two fields in my model:

[Required(ErrorMessage=\"The start date is required\")]
[Display(Name=\"Start Date\")]
[DisplayFormat(DataFormatString =         


        
3条回答
  •  無奈伤痛
    2020-12-04 18:25

    Take a look at Fluent Validation or MVC Foolproof Validation: those can help you a lot.

    With Foolproof for example there is a [GreaterThan("StartDate")] annotation than you can use on your date property.

    Or if you don't want to use other libraries, you can implement your own custom validation by implementing IValidatableObject on your model:

    public class ViewModel: IValidatableObject
    {
        [Required]
        public DateTime StartDate { get; set; }
        [Required]    
        public DateTime EndDate { get; set; } 
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
           if (EndDate < StartDate)
           {
               yield return new ValidationResult(
                   errorMessage: "EndDate must be greater than StartDate",
                   memberNames: new[] { "EndDate" }
              );
           }
        }
    }
    

提交回复
热议问题