I'm trying to implement the client half of a custom validation attribute on MVC 6. The server side works correctly and other client side attributes (like [Required]) work correctly, but my unobtrusive data-val attribute doesn't appear on the rendered field.
Based on what I've seen by trolling the source on Github, I shouldn't need to do anything else. What am I missing here?
[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);
}
}
(Omitting JavaScript code because it's not relevant.)