12
[Required]
[DisplayName("my date")]
public DateTime? DateReg { get; set; }

so if the user is going to pass in an invalid datetime value he will get this message "The value '02.07.201022' is not valid for my date."

how can I translate/localize this message ?

Omu
  • 69,856
  • 92
  • 277
  • 407

1 Answers1

15

Add Messages.resx in App_GlobalResources and in Application_Start in Global.asax:

DefaultModelBinder.ResourceClassKey = "Messages";

Then in the Messages.resx file you could define the following string:

PropertyValueInvalid: The value {0} is invalid for the property {1}

The key needs to be called PropertyValueInvalid.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • from where do you know this stuff :) ? – Omu Jul 01 '10 at 11:22
  • 2
    I have been reading through the ASP.NET MVC source code (thanks MS for providing this) in order to get a better understanding of the inner working of the framework. – Darin Dimitrov Jul 01 '10 at 18:26
  • In my testing I've found that you also need to add `[Required(ErrorMessageResourceType=typeof(Site.Models.Resources.Messages), ErrorMessageResourceName = "RequiredAttribute")]`. Is that right? – Eduardo Molteni Aug 19 '11 at 02:55
  • After more testing, apparently this technique only works when no attributes are attached to the model property or so to say, only when validation is being done with DataTypeAttribute either when it automatically kicks in or when it is attached to the property. For instance, when having DateTime property and you try to send "abc" to it. – mare Oct 13 '11 at 16:31
  • more info: http://weblogs.asp.net/imranbaloch/archive/2013/03/31/localizing-default-error-messages-in-asp-net-mvc-and-web-form.aspx – kloarubeek Mar 25 '14 at 21:49