Using a resx file in the App_GlobalResources directory, I've been able to change the default message for the PropertyValueInvalid string of the model validators.
But it doesn't work to translate the message when a value is required (PropertyValueRequired.)
In the Global.asax.cs Application_Start() I've changed the resource class key, like this:
DefaultModelBinder.ResourceClassKey = "Messages";
And in the Messages.resx files I've put two entries:
- "PropertyValueInvalid" => "O valor '{0}' é inválido para o campo {1}."
- "PropertyValueRequired" = > "É necessário digitar o {0}."
Thanks.
RequiredAttribute not used DefaultModelBinder.GetValueRequiredResource.
Create custom DataAnnotationsModelValidator class.
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter
{
public MyRequiredAttributeAdapter(ModelMetadata metadata,
ControllerContext context,
RequiredAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof (Messages);
attribute.ErrorMessageResourceName = "PropertyValueRequired";
}
}
and register adapter in Global.asax.
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute),
typeof(MyRequiredAttributeAdapter));
Hope this help!
Reusable Validation Error Message Resource Strings for DataAnnotations
This message is baked into System.ComponentModel.DataAnnotations
assembly under the key RequiredAttribute_ValidationError
. You could write a custom validation attribute:
public class MyRequiredAttribute : RequiredAttribute
{
public MyRequiredAttribute()
{
ErrorMessageResourceType = typeof(Messages);
ErrorMessageResourceName = "Required";
}
}
and then inside your Messages.resx
file define the Required
string:
Required => É necessário digitar o {0}.
and finally decorate your view model property with this custom attribute:
public class MyViewModel
{
[MyRequired]
public int Foo { get; set; }
}
How about
[Required (ErrorMessageResourceName="Required",ErrorMessageResourceType=typeof(Messages)]
public string Foo { get; set; }
Required => É necessário digitar o {0}.
Or
Required => {0} field is required.
Please refer below link for complete asp.net mvc localisation guide
asp.net mvc localisation guide
Just add like this
[Required(ErrorMessage = "Your Error Message, here..!")]