I'm using the DataAnnotations attributes along with ASP.Net MVC 2 to provide model validation for my ViewModels:
public class ExamplePersonViewModel {
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
[StringLength(128, ErrorMessageResourceName = "StringLength", ErrorMessageResourceType = typeof(Resources.Validation))]
[DataType(DataType.Text)]
public string Name { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
[DataType(DataType.Text)]
public int Age { get; set; }
}
This seems to work as expected (although it's very verbose). The problem I have is that there are behind-the-scenes model validations being performed that are not tied to any specific attribute. An example of this in the above model is that the Age
property needs to be an int
. If you try to enter a non-integer value on the form, it will error with the following (non-localized) message:
The field Age must be a number.
How can these non-attribute validation messages be localized?
Is there a full list of these messages available so I can make sure they are all localized?
Go to http://forums.asp.net/p/1512140/3608427.aspx, watch the bradwils message dated 01-09-2010, 6:20 PM.
The solution works well for me.
It should be interesting to know the complete list of the messages overridable...
UPDATE
Here the post contents:
Create a global resource class in App_GlobalResources, and set DefaultModelBinder.ResourceClassKey to the name of this class (for example, if you made "Messages.resx", then set ResourceClassKey to "Messages").
There are two strings you can override in MVC 2:
- The string value for "PropertyValueInvalid" is used when the data the user entered isn't compatible with the data type (for example, typing in "abc" for an integer field). The default message for this is: "The value '{0}' is not valid for {1}."
- The string value for "PropertyValueRequired" is used when the user did not enter any data for a field which is not nullable (for example, an integer field). The default message for this is: "A value is required."
It's important to note in the second case that, if you have the DataAnnotationsModelValidatorProvider in your validator providers list (which it is by default), then you will never see this second message. This provider sees non-optional fields and adds an implied [Required] attribute to them so that their messages will be consistent with other fields with explicit [Required] attributes and to ensure that you get client-side validation for required fields.