【问题标题】:Data anntotation attributes. How to set order of execution?数据注释属性。如何设置执行顺序?
【发布时间】:2012-07-13 17:42:36
【问题描述】:

我为出生日期创建了这样的验证属性:

public class DateRequired : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime date = Convert.ToDateTime(value);
            return date != DateTime.MinValue;
        }
    }

    public class DateGraterThanEighteen : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            DateTime date = Convert.ToDateTime(value);
            long ticks = DateTime.Now.Ticks - date.Ticks;
            int years = new DateTime(ticks).Year;
            return years >= 18;
        }
    }

I applied attributes like this

        [DateGraterThanEighteen(ErrorMessage="You must be at least 18")]
        [DateRequired(ErrorMessage = "Date of birth is required")]
        public DateTime DateOfBirth { get; set; }

无论我应用它们的顺序如何,DateGraterThanEighteen 都会首先执行。我怎样才能让 DateRequired 先执行?

【问题讨论】:

    标签: asp.net-mvc-3 attributes data-annotations


    【解决方案1】:

    您可以将订单应用于过滤器。不确定是否可以使用验证属性尝试

    [DateGraterThanEighteen(ErrorMessage="You must be at least 18"), Order=1]
    [DateRequired(ErrorMessage = "Date of birth is required"), Order=2]
    public DateTime DateOfBirth { get; set; }
    

    仅供参考,你拼错了greater :)

    更新:没关系,不能这样做。你需要创建一个ModelValidationProvider

    【讨论】:

      猜你喜欢
      • 2017-01-15
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多