Ben
Ben

Reputation: 1963

ASP.NET Web Api 2 - Change default validation messages for models site wide

Say I have a model, like this:

class Model
{
    [Required]
    public string Name { get; set; }
}

Is there a way to make it so that rather than the error message being:

The Name field is required.

I can change it to:

Name is required.

I would like to do this without making my own attributes and without adding an ErrorMessage = x to all of my attributes.

When searching I found some stuff that seemed to apply to MVC2, but nothing web api specific. I got as far as creating an attribute adapter:

public class CustomRequiredAttributeAdapter : DataAnnotationsModelValidator< RequiredAttribute>
{
    public CustomRequiredAttributeAdapter(ModelMetadata metadata, ModelBindingExecutionContext context, RequiredAttribute attribute)
    : base(metadata, context, attribute)
    {
        attribute.ErrorMessage = "{0} is required.";
    }
}

But registering it like this:

var validatorProvider = new DataAnnotationsModelValidatorProvider();
validatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));       
webApiConfig.Services.Replace(typeof(System.Web.Http.Validation.ModelValidatorProvider), validatorProvider);

in my startup didn't seem to work.

Upvotes: 0

Views: 587

Answers (1)

Ben
Ben

Reputation: 1963

Figured out that I was implementing the wrong type of DataAnnotationsModelValidator

I should have been using the one from the System.Web.Http.Validation.Validators namespace. Like this:

public class CustomRequiredAttributeAdapter : DataAnnotationsModelValidator
{
    public CustomRequiredAttributeAdapter(IEnumerable<ModelValidatorProvider> validatorProviders, ValidationAttribute attribute)
    : base(validatorProviders, attribute)
    {
        attribute.ErrorMessage = "{0} is required.";
    }
}

Then register it as I did above :)

Upvotes: 1

Related Questions