5
votes

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.)

1
I figured the missing bit would be to add a PastDateOnlyAttributeAdapter : DataAnnotationsModelValidator<PastDateOnlyAttribute>, but that didn't solve the problem. It may require a custom IModelValidatorProvider be registered.Ron DeFreitas
Yeah, not sure what's up with it. I hope they fix things in the next update to MVC. Looks like they made a bunch of changes on beta3 that broke a lot of existing documentation.Dustin E

1 Answers

1
votes

An old question, but it appears that this was indeed a bug in the betas. It is all working in the RTM release and the data-val-* attributes are rendered correctly.