c# - 用于验证模型的数据注释,我如何验证它以便日期不在未来?

标签 c# asp.net-mvc validation data-annotations

我有审查模型,我正在尝试验证该模型,以便 当用户选择一个日期时,它不能是 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/

相关文章:

c# - 设置具有相同文本的多个标签

javascript - 无法读取 CKEditor ASP.NET 的 null 属性 'unselectable'

c# - 如何使用最小起订量绕过数据层?

ruby-on-rails - Rails 3 验证多个属性的唯一性

node.js - 在 Mongoose 更新查询中运行自定义验证

用于验证用户个人资料名称的 JavaScript 正则表达式

c# - LINQ 到 SQL : Selecting Name (string) by id (smallint)

javascript - 如何在 onchange 函数之后将值加载到输入中

c# - WPF 网格 IsEnabled 使用 ValueConverter

ASP.NET MVC : Adding selected CSS class to ActionLink if url matches current url