gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:47:14 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com