用于验证模型的DataAnotation,如何验证它以便日期不会在将来?

Jun*_*ung 3 c# validation asp.net-mvc data-annotations

我有一个Review Model,我试图验证该模型,以便当用户选择一个日期时,它不能是将来的日期。

Review.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;}


}
Run Code Online (Sandbox Code Playgroud)

我是新手,文档很难理解。

非常感谢您的提前帮助。

Shy*_*yju 5

您可以创建一个自定义验证属性,该属性执行您的自定义逻辑,并使用它来修饰您的属性名称。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在您的视图模型中,使用此新的自定义属性装饰属性名称

[DateLessThanOrEqualToToday]
public DateTime Date { get; set; }
Run Code Online (Sandbox Code Playgroud)

此自定义验证属性主要侧重于您的特定验证逻辑。您可以根据需要对其进行更改,以包括更多的空值检查,最小值检查等。