Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC 2 - Changing the PropertyValueRequired string

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.

like image 359
daniel Avatar asked Jun 14 '10 19:06

daniel


1 Answers

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

like image 166
takepara Avatar answered Sep 29 '22 02:09

takepara