How to override Entity Framework validation error messages

Paul Taylor picture Paul Taylor · Nov 8, 2012 · Viewed 7.6k times · Source

I have an Entity Framework 4.1 model that supports multiple ASP.NET MVC web applications. I use DataAnnotations to define and localize label text and validation rules and error messages.

For some applications, I need the label text for certain fields to differ from the standard, model-defined text. This is easy to achieve for the labels themselves: I retrieve the text I need from a local resource file, associated with the view. However, the label text is also used in validation error messages such as "{fieldname} must have a maximum length of 50 characters".

What is the best way to alter the validation messages without changing the Annotations on the model classes?

Answer

testCoder picture testCoder · Nov 9, 2012

Try to redefine error messages in controller for specific cases, like this:

Model:

public class Company
    {
        [Required(ErrorMessage = "The field is required")]
        public string CompanyName { get; set; }
        public string Address { get; set; }
    }

controller:

 [HttpPost]
        public ActionResult Index(Company company)
        {
            if(ModelState.IsValid)
            {
                //your code
            }

            // your custom validation message here
            if (ModelState["CompanyName"].Errors.Any())
                ModelState["CompanyName"].Errors[0] = new ModelError("custom error message");

            return View();
        }