1

可能重复:
自定义验证属性 ASP.NET MVC

我设置了一个 Attribute.cs 文件和一个 Models.cs 文件。

在 Models.cs 中,我有:

[Required(ErrorMessage = "*")]
[Display(Name = "DOB")]
public DateTime DOB { get; set; }

[Required(ErrorMessage = "*")]
[Display(Name = "Age")]
[Range(7,12,ErrorMessage = "Age must be between 7-12")]
[DOB()]
public string Age { get; set; }

我在 Attribute.cs 文件中创建了一个自定义验证(DOB函数)。

在该功能中,如何检查该DOB字段并自动分配年龄值?我不确定如何获取 DOB 值。

我的 attribute.cs 中有以下内容,当我在其中放置断点时,它可以很好地执行此功能:

namespace SF.Validation
{
    public class DOBAttribute : ValidationAttribute
    {
        public DOBAttribute(string dob)
        {
            //not sure how to grab DOB value?? Need to do it here.
            //this just validates user input, but need to change to automatically 
            //assign the age based on DOB
            DateTime now = DateTime.Today;
            int age = now.Year - DOB.Year; //DOB.Year isn't grabbing anything
            DateTime birthday = new DateTime(DOB.Year, DOB.Month, DOB.Day);

            if (now < birthday.AddYears(age)) age--;

            if (age < 7 || age > 12)
            {
                IsValid(false);
            }
            else
            {
                IsValid(true);
            }
        }

    }

}
4

0 回答 0