.NET MVC Custom Date Validator

前端 未结 3 2210
谎友^
谎友^ 2020-12-14 04:44

I\'ll be tackling writing a custom date validation class tomorrow for a meeting app i\'m working on at work that will validate if a given start or end date is A) less than t

3条回答
  •  攒了一身酷
    2020-12-14 04:59

    public sealed class DateStartAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dateStart = (DateTime)value;
            // Meeting must start in the future time.
            return (dateStart > DateTime.Now);
        }
    }
    
    public sealed class DateEndAttribute : ValidationAttribute
    {
        public string DateStartProperty { get; set; }
        public override bool IsValid(object value)
        {
            // Get Value of the DateStart property
            string dateStartString = HttpContext.Current.Request[DateStartProperty];
            DateTime dateEnd = (DateTime)value;
            DateTime dateStart = DateTime.Parse(dateStartString);
    
            // Meeting start time must be before the end time
            return dateStart < dateEnd;
        }
    }
    

    and in your View Model:

    [DateStart]
    public DateTime StartDate{ get; set; }
    
    [DateEnd(DateStartProperty="StartDate")]
    public DateTime EndDate{ get; set; }
    

    In your action, just check that ModelState.IsValid. That what you're after?

提交回复
热议问题