我的模型中有这个 DateTime 属性:
[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; }
我希望验证此属性,以便用户无法输入今天之前的日期。如果我要验证一个整数,我可以这样做。
[Range(1, int.MaxValue, ErrorMessage = "Value must be greater than 0")]
但是 range 属性不支持 DateTime 对象。 DateTime 值有类似这样的东西吗?
最佳答案
这应该对你有帮助。
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)
}
}
现在将此属性应用于您的模型属性。
public class SomeModel
{
[Display(Name = "Date of birth")]
[MyDate(ErrorMessage ="Invalid date")]
public DateTime DateOfBirth { get; set; }
}
关于c# - 使用数据注释限制 DateTime 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844747/