使用数据注释进行日期时间(日期和时间)验证

发布于 2024-10-24 08:06:28 字数 428 浏览 7 评论 0原文

我有以下代码:

        [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)而不仅仅是日期。此代码认为 1/1/2011 有效,但实际上不应该,因为它不包含小时,关于如何表达正确格式的任何线索? (日/月/年 时:分)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

羁〃客ぐ 2024-10-31 08:06:28

您可以编写自己的 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;
    }
}

最后,装饰您的属性:

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

注意:要警惕属性上的多个验证属性,因为如果没有更多自定义,则无法确定它们的评估顺序,随后如果验证逻辑重叠,您的错误消息可能无法准确描述你到底是什么意思,财产有问题(是的,这是一个连续的句子)

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)

娜些时光,永不杰束 2024-10-31 08:06:28

最后用自定义 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";
    }
}

Finally solved with a custom 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";
    }
}
耀眼的星火 2024-10-31 08:06:28

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

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

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.

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.

梦醒灬来后我 2024-10-31 08:06:28

此解决方案不允许输入时间 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;
    }
}

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

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

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.

夕色琉璃 2024-10-31 08:06:28

DataTime 变量的验证:在获取模型属性的输入时,可以在 set 属性中使用这些验证来检查输入的格式是否正确。

{
        set
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Kindly enter the date!");
                }
                DateTime date;
                var isValidDate = DateTime.TryParse(value, out date);
                if (isValidDate)
                    dateofpublish = value;
                else
                    throw new Exception("Invalid Date Format");
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Dateofpublish = Console.ReadLine();
            }
        }
        get { return dateofpublish; }
    }

Validation for DataTime Variable : While taking the input for the model properties these validations can be used in the set property to check whether the input is in correct format or not.

{
        set
        {
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    throw new Exception("Kindly enter the date!");
                }
                DateTime date;
                var isValidDate = DateTime.TryParse(value, out date);
                if (isValidDate)
                    dateofpublish = value;
                else
                    throw new Exception("Invalid Date Format");
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Dateofpublish = Console.ReadLine();
            }
        }
        get { return dateofpublish; }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文