Compare Dates DataAnnotations Validation asp.net mvc

前端 未结 5 1545
半阙折子戏
半阙折子戏 2020-12-15 13:11

Lets say I have a StartDate and an EndDate and I wnt to check if the EndDate is not more then 3 months apart from the Start Date

public class DateCompare : V         


        
5条回答
  •  半阙折子戏
    2020-12-15 13:46

    1. Dates

    Entity:

    [MetadataType(typeof(MyEntity_Validation))]
    public partial class MyEntity
    {
    }
    public class MyEntity_Validation
    {
        [Required(ErrorMessage="'Date from' is required")]
        public DateTime DateFrom { get; set; }
    
        [CompareDatesValidatorAttribute("DateFrom")]  
        public DateTime DateTo { get; set; }
    }
    

    Attribute:

     public sealed class CompareDatesValidatorAttribute : ValidationAttribute
    {
        private string _dateToCompare;  
        private const string _errorMessage = "'{0}' must be greater or equal'{1}'";  
    
        public CompareDatesValidatorAttribute(string dateToCompare)
            : base(_errorMessage)
        {
            _dateToCompare = dateToCompare;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(_errorMessage, name, _dateToCompare);
        } 
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var dateToCompare = validationContext.ObjectType.GetProperty(_dateToCompare);
            var dateToCompareValue = dateToCompare.GetValue(validationContext.ObjectInstance, null);
            if (dateToCompareValue != null && value != null && (DateTime)value < (DateTime)dateToCompareValue) 
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }
    

    2. Password

    Entity:

       public string Password { get; set; }
    
        [Compare("Password", ErrorMessage = "ConfirmPassword must match Password")]
        public string ConfirmPassword { get; set; }
    

    I hope it helps

提交回复
热议问题