I am trying to implement the client half of the custom verification attribute on MVC 6. It works correctly on the server side, and other attributes on the client side (for example [Required]) work correctly, but my unobtrusive data-val attribute does not appear on the rendered field.
Based on what I saw while trolling the source on Github, I don't need to do anything. 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 doesn't matter.)
source share