C# attribute to check whether one date is earlier than the other

前端 未结 6 1696
孤独总比滥情好
孤独总比滥情好 2021-02-07 15:05

I have a ViewModel for my MVC4 Prject containing two DateTime properties:

[Required]
[DataType(DataType.Date)]
public DateTime RentDate { get; set; }

[Required]         


        
6条回答
  •  旧巷少年郎
    2021-02-07 15:54

    Model:

    [DateCorrectRange(ValidateStartDate = true, ErrorMessage = "Start date shouldn't be older than the current date")]
    public DateTime StartDate { get; set; }
    
     [DateCorrectRange(ValidateEndDate = true, ErrorMessage = "End date can't be younger than start date")]
    public DateTime EndDate { get; set; }
    

    Attribute class:

    [AttributeUsage(AttributeTargets.Property)]
        public class DateCorrectRangeAttribute : ValidationAttribute
        {
            public bool ValidateStartDate { get; set; }
            public bool ValidateEndDate { get; set; }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                var model = validationContext.ObjectInstance as YourModelType;
    
                if (model != null)
                {
                    if (model.StartDate > model.EndDate && ValidateEndDate
                        || model.StartDate > DateTime.Now.Date && ValidateStartDate)
                    {
                        return new ValidationResult(string.Empty);
                    }
                }
    
                return ValidationResult.Success;
            }
        }
    

提交回复
热议问题