[英]DataAnotation to validate a model, how do I validate it so that the date is not in the future?
我有审核模型,我正在尝试验证模型,以便当用户选择日期时,它不能是将来的日期。
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;}
}
我是新手, 文档很难理解。
非常感谢你的帮助。
您可以创建自定义验证属性,该属性执行您的自定义逻辑并使用它来装饰您的属性名称。
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;
}
}
现在,在您的视图模型中,使用此新的自定义属性装饰您的属性名称
[DateLessThanOrEqualToToday]
public DateTime Date { get; set; }
此自定义验证属性主要关注您的特定验证逻辑。 您可以根据需要更改它以包括更多空检查,最小值检查等。
您需要为此编写自定义验证器。 例如,您可以根据需要为其命名。
[DateNotInTheFuture]
public DateTime Date { get; set; }
本文详细解释了进程本身: https : //msdn.microsoft.com/en-us/library/cc668224.aspx
总结如下:
尝试使用属性进行自定义验证或标准模型验证
第一个选项,在属性标准dataannotations验证上设置属性:
在屏幕上设置显示标签的显示属性。
[DataType(DataType.Date), ErrorMessage = "Please enter a correct date format dd/mm/yyyy hh:mm", DisplayFormat( DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true )] [Range(typeof(DateTime), "1/1/2016", "1/1/2011")] [Display(Name = "My Date")] public DateTime Date {get; set;}
第二个选项, 自定义验证方法 :
您必须扩展ValidationAttribute类并覆盖IsValid
:
public class MyDateValidation: ValidationAttribute
{
public override bool IsValid(object value)
{
// check your business date property
DateTime myDatetime;
bool isParsed = DateTime.TryParse((string)value, out myDatetime);
if(!isParsed)
return false;
return true;
}
}
[MyDateValidation(ErrorMessage="Your message")]
public Datetime myDate { get; set; }
请参阅我关于此主题的其他答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.