作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有审查模型,我正在尝试验证该模型,以便当用户选择一个日期时,它不能是 future 的日期。
评论.cs
public class Review : BaseEntity{
[Key]
public int Id {get; set;}
[Required(ErrorMessage="You need a restaurant name!")]
public string RestaurantName {get; set;}
[What do I put in here??]
public DateTime Date {get; set;}
}
我是新手,documentation有点难以理解。
非常感谢您的提前帮助。
最佳答案
您可以创建一个自定义验证属性来执行您的自定义逻辑,并使用它来装饰您的属性名称。
public class DateLessThanOrEqualToToday : ValidationAttribute
{
public override string FormatErrorMessage(string name)
{
return "Date value should not be a future date";
}
protected override ValidationResult IsValid(object objValue,
ValidationContext validationContext)
{
var dateValue = objValue as DateTime? ?? new DateTime();
//alter this as needed. I am doing the date comparison if the value is not null
if (dateValue.Date > DateTime.Now.Date)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return ValidationResult.Success;
}
}
现在在您的 View 模型中,用这个新的自定义属性装饰您的属性名称
[DateLessThanOrEqualToToday]
public DateTime Date { get; set; }
此自定义验证属性主要关注您的特定验证逻辑。您可以根据需要更改它以包含更多空值检查、最小值检查等。
关于c# - 用于验证模型的数据注释,我如何验证它以便日期不在未来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46184818/
我是一名优秀的程序员,十分优秀!