In ASP.NET MVC 5, value types on models have an implicit [Required]
attribute. I do want this feature, but I want to tweak that attribute, i.e. implicitly apply a different attribute.
So how can I change which attribute is implicitly applied to value types (if at all)?
As far as I know, I could do this:
protected void Application_Start()
{
// System.Web.Mvc.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
}
Then go to each of my models and add a different [Required]
attribute:
public class MyViewModel
{
[MyRequired]
public int Amount { get; set; }
}
Attribute just overrides the default error message now, may want to differ greatly in the future.
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
public MyRequiredAttribute()
{
if (ErrorMessage == null)
{
ErrorMessage = "{0} is required.";
}
}
}
Is there a better approach?
Potentially useful: System.Web.Mvc.DataAnnotationsModelValidatorProvider.cs