After an interesting thread in nhusers, I wrote this is a small post explaining how you can create a simple interpolator for NHibernate Validator that replaces the default messages for your customized ones and as well treats messages for your custom validators. Everything with internationalization using resources.

The first part is to create your own interpolator:

    using System.Globalization;
    using System.Reflection;
    using System.Resources;
    using NHibernate.Validator.Engine;

    public class CustomMessageInterpolator : IMessageInterpolator
        private readonly string ResourceBaseName = "Project.Properties.Validator";

        private readonly ResourceManager resMan;

        public CustomMessageInterpolator()
            this.resMan = new ResourceManager(this.ResourceBaseName, Assembly.GetExecutingAssembly());

        public string Interpolate(string message, IValidator validator, IMessageInterpolator defaultInterpolator)
            var s = GetMessage(message);

            return defaultInterpolator.Interpolate(s, validator, defaultInterpolator);

        private string GetMessage(string message)
            // It's a tempate
            if (!message.StartsWith("{") && !message.EndsWith("}"))
                return message;

            var resource = message.Substring(1, message.Length - 2);

            var m = this.resMan.GetString(resource, CultureInfo.CurrentCulture);

            if (string.IsNullOrEmpty(m))
                // Returns the original message
                return message;

            return m;

I use the same notation as the original project, putting the resource name between { and }. I try to get the string from Validator.resx in the Properties folder of the project and if not found I return the original message. This way, you can override the default messages with your own ones only if you want.

At the end, all messages are passed to the defaultInterpolator, that manages the rest of the substitutions (for example {Max} and {Min} are replaced by the attribute values).

Finally, you have to configure the interpolator in the .config file (it only worked for me in App.config, not in nhvalidator.cfg.xml):

    <section name="nhv-configuration" type="NHibernate.Validator.Cfg.ConfigurationSectionHandler, NHibernate.Validator" />
  <nhv-configuration xmlns="urn:nhv-configuration-1.0">
    <property name="message_interpolator_class">Project.Validation.CustomMessageInterpolator, Project.Validation</property>
    <mapping assembly="Project.Domain" />

And that’s it. I hope it helps.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.