日期时间(日期和时间)与数据验证注释 [英] DateTime (date and hour) validation with Data Annotation

查看:1134
本文介绍了日期时间(日期和时间)与数据验证注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的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; }

我想强制的时间纳入(在格式为hh:mm),而不是只有日期。这code 2011/1/1认为是有效的,当它不应该,因为它不containt小时,任何线索如何前preSS的正确格式? (DD / MM / YYYY HH:MM)

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)

推荐答案

您可以编写自己的 ValidationAttribute 与它装饰的财产。你用自己的逻辑覆盖的IsValid 方法。

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)

这篇关于日期时间(日期和时间)与数据验证注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆