.NET MVC Custom Date Validator

前端 未结 3 2198
谎友^
谎友^ 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?

    0 讨论(0)
  • 2020-12-14 05:03

    I know this post is older, but, this solution I found is much better.

    The accepted solution in this post won't work if the object has a prefix when it is part of a viewmodel.

    i.e. the lines

    // Get Value of the DateStart property
    string dateStartString = HttpContext.Current.Request[DateStartProperty];
    

    A better solution can be found here: ASP .NET MVC 3 Validation using Custom DataAnnotation Attribute:

    New DateGreaterThan attribute:

    public sealed class DateGreaterThanAttribute : ValidationAttribute
    {
        private const string _defaultErrorMessage = "'{0}' must be greater than '{1}'";
        private string _basePropertyName;
    
        public DateGreaterThanAttribute(string basePropertyName) : base(_defaultErrorMessage)
        {
            _basePropertyName = basePropertyName;
        }
    
        //Override default FormatErrorMessage Method
        public override string FormatErrorMessage(string name)
        {
            return string.Format(_defaultErrorMessage, name, _basePropertyName);
        }
    
        //Override IsValid
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //Get PropertyInfo Object
            var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
    
            //Get Value of the property
            var startDate = (DateTime)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
    
            var thisDate = (DateTime)value;
    
            //Actual comparision
            if (thisDate <= startDate)
            {
                var message = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(message);
            }
    
            //Default return - This means there were no validation error
            return null;
        }
    }
    

    Usage example:

    [Required]
    [DataType(DataType.DateTime)]
    [Display(Name = "StartDate")]
    public DateTime StartDate { get; set; }
    
    [Required]
    [DataType(DataType.DateTime)]
    [Display(Name = "EndDate")]
    [DateGreaterThanAttribute("StartDate")]
    public DateTime EndDate { get; set; }
    
    0 讨论(0)
  • 2020-12-14 05:11

    I think this should do it:

    public boolean MeetingIsValid( DateTime start, DateTime end )
    {
          if( start < DateTime.Now || end < DateTime.Now )
              return false;
    
          return start > end || end < start;
    }
    
    0 讨论(0)
提交回复
热议问题