Monday, 9 June 2008

I'm currently developing .NET web application using MonoRail framework and ActiveRecord design pattern. One of the requirements for the project is easy localisation. In general it's pretty straightforward but I had some troubles figuring out how to localize the validation messages coming from ActiveRecord Business Objects.

Of course, you'll need to define those entries in resource files for all languages your application should support (e.g. in Validation.de.resx for German, Validation.es.resx for Spanish, etc.).

Add business objects validation attributesLet's use a sample business object representing User, which only includes name property. We have to add ActiveRecord attributes for validation e.g. ValidateNonEmpty and ValidateLength using appropriate parameters. These both attributes take the validation message as one of the arguments. Instead of giving here the actual message we can use its ID (name) from the resource file e.g. "vldNameRequired". Here is sample code of such Business Object:

For more validation attributes please refer to ActiveRecord documentation.

Catch validation errorsNow, we have to enable validation for appropriate action. Let's say we want to validate data provided by the user while creating new account. For registering new user I've created the Register method together with appropriate data binds. Firstly we need to allow validation for that action (Validate = true). Catching validation errors is described in comments in code below:

Display localized validation messagesNow you have to display validation error messages on the page. This is the sample code that displays all validation errors coming from ActiveRecord validation (I'm using NVelocity as my view engine):

That's it. There are of course many possibilities for implementing that functionality. One of the enhancements could translate the ErrorSummary to the Dictionary<PropertyName, ValidationErrorMsg> so you can display error messages next to appropriate controls.