所以我有这个问题。
我有2个字段Date of birth
和Start 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");
}
}
}
但是当我在模型中应用验证规则时,我会收到此错误
那我该怎么办呢。 善意的。
答案 0 :(得分:0)
属性是元数据,必须在编译时知道,因此必须是常量。您不能传递在运行时之前不知道的属性的值。相反,您传递属性的名称并使用反射来获取属性的值。
通常,您使用属性修饰模型属性,因此只需传递其他属性的名称,而不是dob
和startDate
。另外,您的属性不允许灵活性,因为您在方法中对年龄进行了硬编码,并且该值也应该传递给方法,以便可以将其用作(例如)
[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.js
和jquery.validate.unobtrusive.js
插件为您提供客户端验证。有关更多详细信息,请参阅THE COMPLETE GUIDE TO VALIDATION IN ASP.NET MVC 3 - PART 2