Validation message localization without resource files

Topics: Validation Application Block
Jan 11, 2011 at 9:13 PM

I'm validating objects using configuration and would like to use other than resource files for localization.

Is it possible to access the validator objects and change their message templates after I have instantiated the ConfigurationValidatorFactory object and before I do the validation?

So far I have only managed to access the validators after validating the object and then the message has already been constructed and changing the template then will not change the message anymore.



Jan 11, 2011 at 11:38 PM
Edited Jan 12, 2011 at 11:12 AM

Changing the Templates of validators isn't possible and would be a bad idea, because validators can be cached and used across threads and you will end up with race conditions in multi-threaded applications (this would result in showing German error messages to your English users for instance).

What might work for you is having a validation configuration file per language and switch at runtime between the configurations. Down side is that you have duplicate validation configuration, but it might do the trick for you.

You can create an implementation of IConfigurationSource that determines dynamically which configuration to return. Such a class could look like this:


public class MultiLanguageConfigurationSource
    : IConfigurationSource
    public ConfigurationSection GetSection(string sectionName)
        string culture = CultureInfo.CurrentCulture.Name;
        var source = new FileConfigurationSource(
            "validation." + culture + ".config");
        return source.GetSection(sectionName);

    #region IConfigurationSource Members

    // Rest of the IConfigurationSource members left out.
    // Just implement them by throwing an exception from
    // their bodies; they are not used.



You can register this type in the enterprise library configuration or create an instance and supply it to the ValidationFactory as follows:


var validator = ValidationFactory.CreateValidator(typeToValidate, 
    string.Empty, new MultiLanguageConfigurationSource());



Jan 12, 2011 at 4:07 PM
Edited Jan 12, 2011 at 4:20 PM


I think it would be really great idea to be able to change the template at runtime, but apparently not advisable due its technical restrictions.


Your sample of the IConfigurationSource implementation solves my problem.  Instead of duplicating the rules I think I will change the template attributes dynamically in one config file.


Many Thanks,