Providing localized error messages for non-attributed model validation in ASP.Net MVC 2?
Asked Answered
T

3

20

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?

Tribadism answered 19/3, 2010 at 21:1 Comment(0)
P
19

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.

Pokorny answered 31/3, 2010 at 8:38 Comment(3)
Additional information I found as well: #1539373Tribadism
It is important to note that by doing this you will only have localized error message while validating on the SERVER-SIDE. To have your localized message on the client side aswell you WILL need to copy and paste ClientDataTypeModelValidatorProvider from MVC source and rewrite it's MakeErrorString method. More info here, scroll to the enda. I took me a hell of a lot of time to figure out that client side and server side both use different means for getting that message. Hope this helps someone to save time.Amador
You say that the second message will never be shown if you have DataAnnotationsModelValidatorProvider in the validator providers list. How can I overcome this problem?Casper
P
7

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
Prosaism answered 13/6, 2011 at 14:39 Comment(3)
Thanks! Where did you get this list?Casper
It was long time ago, but as I recall it was either something that I printed with reflexion, or more probably digged out with ILSpyProsaism
For MVC 5 System.Web.MVC has a Resources folder specifying the resources-file for System.Web.Mvc.Properties.MvcResources.resources with all resource names and messagesHumour
R
0

Simple way to specify message for Localization Error Message like Integer , Double , Float you can do it Following way.

[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resources.Validation))]
[Range(0, int.MaxValue, ErrorMessageResourceName = "ValidateAge", ErrorMessageResourceType = typeof(Resources.Validation))]
[DataType(DataType.Text)]
public string Age { get; set; }

So instead of using Integer , double and Float use string with Range attribute and specify your custom Localization Error Message with it.

Rosenstein answered 24/7, 2014 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.