使用数据注释限制DateTime值 [英] Restrict DateTime value with data annotations

查看:78
本文介绍了使用数据注释限制DateTime值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中具有以下DateTime属性:

I have this DateTime attribute in my model:

[Required(ErrorMessage = "Expiration Date is required")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
[DisplayName("Expiration Date")]
public DateTime? ExpirationDate { get; set; }

我希望验证此属性,以便用户无法输入今天之前的日期.如果我要验证整数,则可以执行此操作.

I'd like this attribute to be validated so that the user can't enter a date that occurred before today. If I was validating an integer, I could do this.

[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")]

但是range属性不支持DateTime对象. DateTime值是否有类似的内容?

But the range attribute doesn't support a DateTime object. Is there something like this for a DateTime value?

推荐答案

这应该对您有所帮助.

This should help you.

public class MyDateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)// Return a boolean value: true == IsValid, false != IsValid
    {
        DateTime d = Convert.ToDateTime(value);
        return d >= DateTime.Now; //Dates Greater than or equal to today are valid (true)

    }
}

现在将此属性应用于模型"属性.

Now apply this attribute to your Model property.

    public class SomeModel
    {
       [Display(Name = "Date of birth")]
       [MyDate(ErrorMessage ="Invalid date")]
       public DateTime DateOfBirth { get; set; }
    } 

这篇关于使用数据注释限制DateTime值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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