Logo

NHibernate

The object-relational mapper for .NET

How to

This page is converted from the old nhforge.org Wiki. First published by: Marc Climent on 03-04-2009, Last revision by: Marc Climent on 03-10-2009

Create a custom message interpolator for NHibernate Validator

The default interpolator is quite complete and complex but you can use its power while using your own messages. This messages can replace the original messages or can be the localized messages of your own validator.

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):

<configuration>
  <configsections>
    <section name="nhv-configuration"

        type="NHibernate.Validator.Cfg.ConfigurationSectionHandler, NHibernate.Validator">

    </section>
    <nhv-configuration>
      <property name="message_interpolator_class">

        Project.Validation.CustomMessageInterpolator, Project.Validation

      </property>
      <mapping assembly="Project.Domain">
      </mapping>
    </nhv-configuration>
  </configsections>
</configuration>

And that's it. I hope it helps.

© NHibernate Community 2024