Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Validation Attribute not rendering client side validation attribute

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

like image 965
Dustin E Avatar asked Nov 10 '22 17:11

Dustin E


1 Answers

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.

like image 198
Paul Hiles Avatar answered Nov 15 '22 05:11

Paul Hiles