我设置了一个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);
}
}
}
}