localize data annotations default messages ([Required] [StringLength] etc.)

Omu picture Omu · Sep 21, 2010 · Viewed 19.9k times · Source

if I decorate the properties of my ViewModels with attributes like this:

public class Vm
{

[Required]
[StringLength(35)]
public string Name {get;set;}

}

I am going to get english validation messages:

"this field is required"
"The field Name must be a string with a maximum length of 35"

how could I translate them ?

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 21, 2010

You could use the ErrorMessageResourceName property:

[Required(ErrorMessageResourceName = "SomeResource")]
[StringLength(30, ErrorMessageResourceName = "SomeOtherResource")]
public string Name { get; set; }

You may checkout this blog post for an example.


UPDATE:

In Application_Start:

DefaultModelBinder.ResourceClassKey = "Messages";

And in the Messages.resx file you need to add the custom error messages. Use Reflector to look at the System.Web.Mvc and System.ComponentModel.DataAnnotations assemblies in order to see the key names to use.