我正在尝试在MVC 6上实现客户端一半的自定义验证属性。服务器端正常工作,其他客户端属性(如[Required])正常工作,但我的不显眼的data-val属性没有出现在渲染字段上。
根据我在Github上浏览源代码看到的内容,我不需要做任何其他事情。我在这里错过了什么?
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class PastDateOnlyAttribute : ValidationAttribute, IClientModelValidator
{
private const string DefaultErrorMessage = "Date must be earlier than today.";
public override string FormatErrorMessage(string name)
{
return DefaultErrorMessage;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ClientModelValidationContext context)
{
var rule = new ModelClientValidationPastDateOnlyRule(FormatErrorMessage(context.ModelMetadata.GetDisplayName()));
return new[] { rule };
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
var now = DateTime.Now.Date;
var dte = (DateTime)value;
if (now <= dte) {
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
public class ModelClientValidationPastDateOnlyRule : ModelClientValidationRule
{
private const string PastOnlyValidateType = "pastdateonly";
private const string MaxDate = "maxdate";
public ModelClientValidationPastDateOnlyRule(
string errorMessage)
: base(validationType: PastOnlyValidateType, errorMessage: errorMessage)
{
ValidationParameters.Add(MaxDate, DateTime.Now.Date);
}
}
(省略JavaScript代码,因为它不相关。)
答案 0 :(得分:1)
一个老问题,但似乎这确实是测试版中的一个错误。它全部在RTM版本中工作,并且data-val- *属性被正确呈现。