asp.net-mvc 使用数据注释的日期时间(日期和小时)验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5390403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:01:19  来源:igfitidea点击:

DateTime (date and hour) validation with Data Annotation

asp.net-mvcdatetimedata-annotations

提问by Marc

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)

我想强制包含时间(格式为 hh:mm)而不仅仅是日期。此代码认为 2011 年 1 月 1 日是有效的,因为它不应该包含小时,有关如何表达正确格式的任何线索?(dd/mm/yyyy hh:mm)

回答by David Fox

You could write your own ValidationAttributeand decorate the property with it. You override the IsValidmethod with your own logic.

您可以自己编写ValidationAttribute并用它来装饰属性。您可以IsValid使用自己的逻辑覆盖该方法。

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)

注意:请注意您的属性上的多个验证属性,因为如果没有更多的自定义,它们的评估顺序将无法确定,随后如果验证逻辑重叠,您的错误消息可能无法准确描述您的错误含义与财产(是的,这是一个连续的句子)

回答by Marc

Finally solved with a custom ValidationAttribute :

最后用自定义 ValidationAttribute 解决了:

public class DateTimeValidation : RegularExpressionAttribute {
    public DateTimeValidation()
        : base(@"^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2})) (20|21|22|23|[0-1]?\d):[0-5]?\d$") {
        ErrorMessage = "Date must be in the format of : dd/mm/yyyy hh:mm";
    }
}

回答by Alex Shkor

This solution doesn't allow to input time 00.00, but will work with another values.

此解决方案不允许输入时间 00.00,但可以使用其他值。

public class TimeRequiredAttribute : ValidationAttribute
{
    protected override IsValid(object value)
    {
        DateTime result;
        bool parsed = DateTime.TryParse((string)value, out result);
        if(!parsed && DateTime.MinValue.TimeOfDay == result.TimeOfDay)
        {
           return false;
        }
        return true;
    }
}

But it will work only with string proprety.

但它仅适用于字符串属性。

回答by DAK

If you just pass date in a string it will consider it as 12:00 AM. If you want to pass time within a string use "06/06/2011 7:00 PM" syntax.

如果您只是在字符串中传递日期,它会将其视为 12:00 AM。如果您想在字符串中传递时间,请使用“06/06/2011 7:00 PM”语法。

Other workaround would be to keep your string as is, convert it to DateTime & then AddHours &/or AddMinutes to DateTime object depending on your needs.

其他解决方法是保持字符串原样,根据需要将其转换为 DateTime,然后将 AddHours 和/或 AddMinutes 转换为 DateTime 对象。