Override Existing Data Annotation Attribute in asp.net core 1.1

1.8k views Asked by At

I am trying to override the RequiredAttribute in .net core and does not seem to work on asp.net core 1.1

Here is the test code

public class CustomRequiredAttribute : RequiredAttribute
{
    public CustomRequiredAttribute():base()
    {

    }

    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return base.IsValid(value, validationContext);
    }

}

Once used on my model I am expecting the normal result like field is required as I have not customized it yet and just calling base methods.

This does not seem to work as expected and just bypasses the required on both the client and server side.

The purpose of this is to add a validation message pulled from a db to the ErrorMessage property.

1

There are 1 answers

3
Axel Heer On

Your problem is that the ValidationAttributeAdapterProvider, which is the default implementation of IValidationAttributeAdapterProvider, checks for specific types only. Thus, using custom implementations leads to missing "adapter providers", which leads to missing data attributes.

Solution: provide your own implementation of IValidationAttributeAdapterProvider, which can forward to the default implementation for non custom stuff...

public class CustomValidationAttributeAdapterProvider : IValidationAttributeAdapterProvider
{
    private IValidationAttributeAdapterProvider innerProvider = new ValidationAttributeAdapterProvider();

    public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
    {
        if (attribute == null)
            throw new ArgumentNullException(nameof(attribute));

        var type = attribute.GetType();

        if (type == typeof(CustomRequiredAttribute))
            return new RequiredAttributeAdapter((RequiredAttribute)attribute, stringLocalizer);

        return innerProvider.GetAttributeAdapter(attribute, stringLocalizer);
    }
}

...and register it as a singleton.

services.AddSingleton<IValidationAttributeAdapterProvider, CustomValidationAttributeAdapterProvider>();