【问题标题】:How to get model instance in a custom validation attribute如何在自定义验证属性中获取模型实例
【发布时间】: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


    【解决方案1】:

    以下是两种无需硬编码模型名称的简单方法:

    1.第一种方式:

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var model = (DateTime)value;
            var db = model.AddYears(100);
            if (model == null)
                throw new ArgumentException("Attribute not applied on Model");
            if (model > DateTime.Now.Date)
                return new ValidationResult($"{validationContext.DisplayName} can't be in future");
            if (model > 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;
        }
    

    2.第二种方式:

    public class FormModel: IValidatableObject
    {
        [Required, Display(Name = "Date of Birth")]
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        public DateTime DOB { get; set; }
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var data = DOB.AddYears(100);
            if (DOB> DateTime.Now.Date)
            {
                yield return new ValidationResult("Date of Birth can't be in future");
                yield break;
            }
            if (DOB> DateTime.Now.Date.AddYears(-16))
            {
                yield return new ValidationResult("You must be 17 years old.");
                yield break;
            }
            if (data < DateTime.Now.Date)
            {
                yield return new ValidationResult("We rescept you but we cannot accept this date. over 100 years old.");
                yield break;
            }
        }
    }
    

    【讨论】:

    • ...谢谢..它有效...我使用了您提供的第一个选项。但附带说明...我认为这仅适用于日期时间属性...如果我们必须处理其他类型的模型属性,那么我们必须找到其他出路,因为这是特定于日期时间属性的。不是吗。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多