数据注释属性。如何设置执行顺序?

时间:2012-07-13 20:22:36

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

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

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先执行?

1 个答案:

答案 0 :(得分:0)

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

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

仅供参考,你拼错了更多:)

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