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.
List of messages (MVC 3.0):
ActionMethodSelector_AmbiguousMatch
ActionMethodSelector_AmbiguousMatchType
AsyncActionMethodSelector_AmbiguousMethodMatch
AsyncActionMethodSelector_CouldNotFindMethod
AsyncCommon_AsyncResultAlreadyConsumed
AsyncCommon_ControllerMustImplementIAsyncManagerContainer
AsyncCommon_InvalidAsyncResult
AsyncCommon_InvalidTimeout
AuthorizeAttribute_CannotUseWithinChildActionCache
ChildActionOnlyAttribute_MustBeInChildRequest
ClientDataTypeModelValidatorProvider_FieldMustBeNumeric
Common_NoRouteMatched
Common_NullOrEmpty
Common_PartialViewNotFound
Common_PropertyCannotBeNullOrEmpty
Common_PropertyNotFound
Common_TriState_False
Common_TriState_NotSet
Common_TriState_True
Common_TypeMustDriveFromType
Common_ValueNotValidForProperty
Common_ViewNotFound
CompareAttribute_MustMatch
CompareAttribute_UnknownProperty
Controller_UnknownAction
Controller_UpdateModel_UpdateUnsuccessful
Controller_Validate_ValidationFailed
ControllerBase_CannotExecuteWithNullHttpContext
ControllerBase_CannotHandleMultipleRequests
ControllerBuilder_ErrorCreatingControllerFactory
ControllerBuilder_FactoryReturnedNull
ControllerBuilder_MissingIControllerFactory
CshtmlView_ViewCouldNotBeCreated
CshtmlView_WrongViewBase
DataAnnotationsModelMetadataProvider_UnknownProperty
DataAnnotationsModelMetadataProvider_UnreadableProperty
DataAnnotationsModelValidatorProvider_ConstructorRequirements
DataAnnotationsModelValidatorProvider_ValidatableConstructorRequirements
DefaultControllerFactory_ControllerNameAmbiguous_WithoutRouteUrl
DefaultControllerFactory_ControllerNameAmbiguous_WithRouteUrl
DefaultControllerFactory_ErrorCreatingController
DefaultControllerFactory_NoControllerFound
DefaultControllerFactory_TypeDoesNotSubclassControllerBase
DefaultModelBinder_ValueInvalid
DefaultModelBinder_ValueRequired
DefaultViewLocationCache_NegativeTimeSpan
DependencyResolver_DoesNotImplementICommonServiceLocator
ExceptionViewAttribute_NonExceptionType
ExpressionHelper_InvalidIndexerExpression
FilterAttribute_OrderOutOfRange
HtmlHelper_InvalidHttpMethod
HtmlHelper_InvalidHttpVerb
HtmlHelper_MissingSelectData
HtmlHelper_TextAreaParameterOutOfRange
HtmlHelper_ValidationParameterCannotBeEmpty
HtmlHelper_ValidationParameterMustBeLegal
HtmlHelper_ValidationTypeCannotBeEmpty
HtmlHelper_ValidationTypeMustBeLegal
HtmlHelper_ValidationTypeMustBeUnique
HtmlHelper_WrongSelectDataType
JsonRequest_NotAllowed
ModelBinderAttribute_ErrorCreatingModelBinder
ModelBinderAttribute_TypeNotIModelBinder
ModelBinderDictionary_MultipleAttributes
ModelMetadata_PropertyNotSettable
MvcRazorCodeParser_CannotHaveModelAndInheritsKeyword
MvcRazorCodeParser_ModelKeywordMustBeFollowedByTypeName
MvcRazorCodeParser_OnlyOneModelStatementIsAllowed
OutputCacheAttribute_CannotNestChildCache
OutputCacheAttribute_ChildAction_UnsupportedSetting
OutputCacheAttribute_InvalidDuration
OutputCacheAttribute_InvalidVaryByParam
PrivateAssociatedMetadataTypeTypeDescriptor_MetadataTypeContainsUnknownProperties
RedirectAction_CannotRedirectInChildAction
ReflectedActionDescriptor_CannotCallInstanceMethodOnNonControllerType
ReflectedActionDescriptor_CannotCallMethodsWithOutOrRefParameters
ReflectedActionDescriptor_CannotCallOpenGenericMethods
ReflectedActionDescriptor_CannotCallStaticMethod
ReflectedActionDescriptor_ParameterCannotBeNull
ReflectedActionDescriptor_ParameterNotInDictionary
ReflectedActionDescriptor_ParameterValueHasWrongType
ReflectedAsyncActionDescriptor_CannotExecuteSynchronously
ReflectedParameterBindingInfo_MultipleConverterAttributes
RemoteAttribute_NoUrlFound
RemoteAttribute_RemoteValidationFailed
RequireHttpsAttribute_MustUseSsl
SessionStateTempDataProvider_SessionStateDisabled
SingleServiceResolver_CannotRegisterTwoInstances
SynchronizationContextUtil_ExceptionThrown
TemplateHelpers_NoTemplate
TemplateHelpers_TemplateLimitations
Templates_TypeMustImplementIEnumerable
TypeCache_DoNotModify
ValidatableObjectAdapter_IncompatibleType
ValueProviderResult_ConversionThrew
ValueProviderResult_NoConverterExists
ViewDataDictionary_ModelCannotBeNull
ViewDataDictionary_WrongTModelType
ViewMasterPage_RequiresViewPage
ViewPageHttpHandlerWrapper_ExceptionOccurred
ViewStartPage_RequiresMvcRazorView
ViewUserControl_RequiresViewDataProvider
ViewUserControl_RequiresViewPage
WebFormViewEngine_UserControlCannotHaveMaster
WebFormViewEngine_ViewCouldNotBeCreated
WebFormViewEngine_WrongViewBase
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With