【问题标题】:Apply custom validation in Asp.Net MVC Model throw object reference error在 Asp.Net MVC 模型中应用自定义验证抛出对象引用错误
【发布时间】:2016-06-26 13:23:05
【问题描述】:

所以我有这个问题。

我有 2 个字段是 Date of birthStart working date。如果

开始工作日期 - 出生日期 >= 22

然后是有效的。所以这是我的代码

[AttributeUsage(AttributeTargets.Property)]
    public class MiniumAgeAttribute:ValidationAttribute
    {
        private DateTime dob { get; set; }
        private DateTime startDate { get; set; }
        public MiniumAgeAttribute(DateTime DOB, DateTime StartDate)
        {
            dob = DOB;
            startDate = StartDate;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            int age;
            age = startDate.Year - dob.Year;
            if (age >= 22)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult("Age is required to be 22 or more");
            }

        }
}

但是当我在模型中应用我的验证规则时,我得到了这个错误

那么我该如何解决它。 亲切的问候。

【问题讨论】:

    标签: asp.net-mvc validation model


    【解决方案1】:

    属性是元数据,必须在编译时知道,因此必须是常量。您不能传递直到运行时才知道的属性的值。相反,您传递属性的名称并使用反射来获取属性的值。

    通常你用属性来装饰模型属性,所以它只需要传递另一个属性的名称,而不是dobstartDate。此外,您的属性不允许任何灵活性,因为您在方法中硬编码了年龄,并且该值也应该传递给方法,以便它可以用作(比如说)

    [MiminumAge(22, "DateOfBirth")] // or [MiminumAge(18, "DateOfBirth")]
    public DateTime StartDate { get; set; }
    public DateTime DateOfBirth { get; set; }
    

    您的逻辑也不正确,因为startDate.Year - dob.Year 没有考虑日期的日和月值。

    你的属性应该是

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class MiminumAgeAttribute : ValidationAttribute
    {
        private const string _DefaultErrorMessage = "You must be at least {0} years of age.";
        private readonly string _DOBPropertyName;
        private readonly int _MinimumAge;
    
        public MiminumAgeAttribute (string dobPropertyName, int minimumAge)
        {
            if (string.IsNullOrEmpty(dobPropertyName))
            {
                throw new ArgumentNullException("propertyName");
            }
            _DOBPropertyName= dobPropertyName;
            _MinimumAge = minimumAge;
            ErrorMessage = _DefaultErrorMessage;
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DatetTime startDate;
            DateTime dateOfBirth;
            bool isDateValid = DateTime.TryParse((string)value, out startDate);
            var dobPropertyName = validationContext.ObjectInstance.GetType().GetProperty(_DOBPropertyName);
            var dobPropertyValue = dobPropertyName.GetValue(validationContext.ObjectInstance, null);
            isDOBValid = DateTime.TryParse((string)dobPropertyValue, out dateOfBirth);
            if (isDateValid && isDOBValid)
            {
                int age = startDate.Year - dateOfBirth.Year;
                if (dateOfBirth > startDate.AddYears(-age))
                {
                    age--;
                }
                if (age < _MinimumAge)
                {
                    return new ValidationResult(string.Format(ErrorMessageString, _MinimumAge));
                }
            }
            return ValidationResult.Success;
        }
    }
    

    您还可以通过实现IClientValidatable 并将脚本添加到视图以使用jquery.validate.jsjquery.validate.unobtrusive.js 插件为您提供客户端验证来进一步增强此功能。更多详情请参考THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3 - PART 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      相关资源
      最近更新 更多