MVC model validation for date

前端 未结 4 1826
别跟我提以往
别跟我提以往 2020-11-27 22:42

Is there any default validation for MVC 5 where I can set min and max value of date?

In my model i want date validation

    public class MyClass
             


        
4条回答
  •  臣服心动
    2020-11-27 23:27

    I'd do this with the IValidatableObject interface from System.ComponentModel.DataAnnotations, which allows you to add extra validation rules where you can do a lot more checking. Add the interface to your class, and then implement the Validate method, where you can compare the StartDateTime against the current date/time, and also compare the EndDateTime with the StartDateTime, e.g.

    public class MyClass : IValidatableObject
    {               
        [Required(ErrorMessage="Start date and time cannot be empty")]
        //validate:Must be greater than current date
        [DataType(DataType.DateTime)]
        public DateTime StartDateTime { get; set; }
    
        [Required(ErrorMessage="End date and time cannot be empty")]
        //validate:must be greater than StartDate
        [DataType(DataType.DateTime)]
        public DateTime EndDateTime { get; set; }       
    
        public IEnumerable Validate(ValidationContext validationContext)
        {
            List results = new List();
    
            if (StartDateTime < DateTime.Now)
            {
                results.Add(new ValidationResult("Start date and time must be greater than current time", new []{"StartDateTime"}));
            }
    
            if (EndDateTime <= StartDateTime)
            {
                results.Add(new ValidationResult("EndDateTime must be greater that StartDateTime", new [] {"EndDateTime"}));
            }
    
            return results;
        }     
    }
    

    The only potential drawback to this is that Validate runs server-side, not in jQuery validation.

提交回复
热议问题