Skip to content

Model Validation Message for ASP.NET and EntityFramework

Rick Strahl edited this page Jul 5, 2015 · 4 revisions

ASP.NET and Entity Framework support model validation and you can also use the database provider to localize these validation messages. To do so you have to generate strongly typed resources or export to Resx and then enable strong resource typing. Model validation works of object properties so in order to use it a type has to exist.

To do this:

  • Open the Localization Administration form
  • Use Export Class to export create strongly typed classes from each ResourceSet
  • Or: Use Export to Resx to export Resx files (in Project mode), then make sure to enable the strong type generation on the Resx and choose Public class .

Once either of these has been done, you have strongly typed resources classes that you can use as your Validation ErrorMessageResourceName (the ResourceId) and Type:

public class ViewModelWithLocalizedAttributes
{
    [Required(ErrorMessageResourceName = "NameIsRequired", ErrorMessageResourceType = typeof(Resources))]
    public string Name { get; set;  }

    [Required(ErrorMessageResourceName = "AddressIsRequired", ErrorMessageResourceType = typeof(Resources))]
    public string Address { get; set;  }
}

The type will be your exported class or generated Resx class and the name is the name of the property on the generated object. DataAnnotations use Reflection to lookup the property name, so if for some reason the validation does not work check the following:

  • Make sure the property name is typed correctly and matches a property name.
  • Try writing out the actually property using @Resources.AddressIsRequired to ensure the value is valid (on a simple test page perferrably).