Localizing data annotation error messages

Topics: Localization
Sep 3, 2012 at 9:47 AM
Edited Sep 18, 2012 at 12:42 PM


I am not able to get data annotation localization to work.

I am using Orchard's Q42 module for localization, we could localize the text in views simply using @T helper. However, for localizing data annotation error messages I have followed http://orchard.codeplex.com/discussions/266275 discussion. As discussed in this, I have created the following custom attribute class.

 public class RequiredFieldAttribute : RequiredAttribute
        public RequiredFieldAttribute()
            T = NullLocalizer.Instance;

        public Localizer T { get; set; }

        public override string FormatErrorMessage(string name)
            return T("The {0} field is required.", name).Text;

My module class looks like below (registering providers to get client side validation to work).

// http://orchard.codeplex.com/discussions/278362

   public class MyModule : Module


       protected override void Load(ContainerBuilder builder)




           // Register the objects



           // FIX: to get the default MVC 3 client-side validation for Data Annotations in the server side model


           ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());

           ModelValidatorProviders.Providers.Add(new DataErrorInfoModelValidatorProvider());

           ModelValidatorProviders.Providers.Add(new ClientDataTypeModelValidatorProvider());



In view model we are using custom attribute for the property as below.

[RequiredField(ErrorMessage = "Selecteer minstens een klasse.")]

public string SelectedCabinClasses { get; set; }

This model property is bound to a hidden field in the view, the hidden field is being updated with specific value based the checkbox checked in UI and if the hidden field is empty then the application should show the required validation message.

@Html.HiddenFor(model => model.SelectedCabinClasses)

So, when we use custom data annotation attribute for the model property (i.e. RequiredField) then the validation message is not being displayed even though the field validation is failed. If we use System.ComponentModel.DataAnnotations.Required then the validation message is being shown.

From our investigation, we found that the required attributes (“data-val-required” and “data-val”) are not being associated to hidden field if we use RequiredField attribute for model property. If we use System.ComponentModel.DataAnnotations.Required for model property then these attributes are being associated to hidden field and it works fine.

I am not sure, what is going wrong. Can anyone help on this?


Ambrish Atlapure

Oct 12, 2012 at 2:01 PM

Any hints on this?


Oct 12, 2012 at 4:40 PM

Use LocalizedRequiredAttribute instead.