【发布时间】:2019-09-11 14:28:41
【问题描述】:
我正在使用 asp.net core 2.0,并且我有一个用于验证年龄的自定义验证属性。
public class ValidAgeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var model = validationContext.ObjectInstance as FormModel;
var db = model.DOB.AddYears(100);
if (model == null)
throw new ArgumentException("Attribute not applied on Model");
if (model.DOB > DateTime.Now.Date)
return new ValidationResult($"{validationContext.DisplayName} can't be in future");
if (model.DOB > DateTime.Now.Date.AddYears(-16))
return new ValidationResult("You must be 17 years old.");
if (db < DateTime.Now.Date)
return new ValidationResult("We rescept you but we cannot accept this date. over 100 years old.");
return ValidationResult.Success;
}
}
但是这个属性取决于我的“FormModel”类,这是我的领域模型类。
public class FormModel
{
[Required, Display(Name = "Date of Birth")]
[ValidAge]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DOB { get; set; }
}
我希望这个属性不依赖于“FormModel”类,如此处所示。那么我能否以某种方式获取我正在使用此属性的模型的实例,而不必在此处硬编码模型的名称?
【问题讨论】:
标签: asp.net-core asp.net-core-2.0