Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

asp.net mvc - DateTime (date and hour) validation with Data Annotation

I have the following code:

        [DisplayName("58.Date and hour of birth")]
        [DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy hh:mm")]
        [Range(typeof(DateTime), "1/1/2011", "1/1/2016")]
        [RequiredToClose]
        public object V_58 { get; set; }

I want to force the inclusion of time (in format hh:mm) and not only the date. This code considers 1/1/2011 as valid when it shouldn't as it does not containt the hour , Any clue about how to express the correct format ? (dd/mm/yyyy hh:mm)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...