mvc4 data annotation compare two dates

前端 未结 3 1577
独厮守ぢ
独厮守ぢ 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条回答
  •  -上瘾入骨i
    2020-12-04 18:28

    IValidatableObject interface provides a way for an object to be validated which implements IValidatableObject.Validate(ValidationContext validationContext) method. This method always return IEnumerable object. That's why you should create list of ValidationResult objects and errors are added to this and return. Empty list means to validate your conditions. That is as follows in mvc 4...

     public class LibProject : IValidatableObject
    {
        [Required(ErrorMessage="Project name required")]
    
        public string Project_name { get; set; }
        [Required(ErrorMessage = "Job no required")]
        public string Job_no { get; set; }
        public string Client { get; set; }
        [DataType(DataType.Date,ErrorMessage="Invalid Date")]
        public DateTime ExpireDate { get; set; }
    
    
        IEnumerable IValidatableObject.Validate(ValidationContext validationContext)
        {
            List < ValidationResult >  res =new List();
            if (ExpireDate < DateTime.Today)
            {
                ValidationResult mss=new ValidationResult("Expire date must be greater than or equal to Today");
                res.Add(mss);
    
            }
            return res; 
        }
    }
    

提交回复
热议问题