我写了一个简单的自定义验证器。它适用于表单提交,但不像我认为的那样在客户端实时。这段代码是否正确?我需要在View上做些什么吗?对于记录,其他(内置)验证器在客户端工作。我甚至添加了
@{
Html.EnableClientValidation(true);
ViewBag.Title = "CaseVue | Patient";
}
到视图的顶部。这是我的验证码:
public class BirthDateRangeAttribute : ValidationAttribute, IClientValidatable
{
public int MaxAge { get; set; }
public BirthDateRangeAttribute()
{
}
public override bool IsValid(object value)
{
string val = value.ToString();
if (!string.IsNullOrWhiteSpace(val))
{
DateTime dt;
if (DateTime.TryParse(val, out dt))
{
return dt >= DateTime.Now.AddYears(MaxAge * -1) && dt <= DateTime.Now;
}
else
{
return false;
}
}
return false;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule {
ErrorMessage = this.ErrorMessage,
ValidationType = "birthdaterange"
};
rule.ValidationParameters.Add("maxage", this.MaxAge);
yield return rule;
}
}
任何人都能看到我做错了什么?