DateTime (date and hour) validation with Data Annotation

前端 未结 4 2163
醉话见心
醉话见心 2020-11-29 10:03

I have the following code:

        [DisplayName(\"58.Date and hour of birth\")]
        [DataType(DataType.DateTime, ErrorMessage = \"Please enter a valid da         


        
4条回答
  •  一生所求
    2020-11-29 10:48

    You could write your own ValidationAttribute and decorate the property with it. You override the IsValid method with your own logic.

    public class MyAwesomeDateValidation : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime dt;
            bool parsed = DateTime.TryParse((string)value, out dt);
            if(!parsed)
                return false;
    
            // eliminate other invalid values, etc
            // if contains valid hour for your business logic, etc
    
            return true;
        }
    }
    

    And finally, decorate your property:

    [MyAwesomeDateValidation(ErrorMessage="You were born in another dimension")]
    public object V_58 { get; set; }
    

    Note: Be wary of multiple validation attributes on your properties, as the order in which they are evaluated is unable to be determined without more customization, and subsequently if validation logic overlaps, your error messages might not accurately describe what exactly you mean to be wrong with the property (yeah, that's a run-on sentence)

提交回复
热议问题