Using a Resource File for NHibernate Validation Messages

I have recently started using NHibernate for a project because I wanted something that would work in Mono on linux and coupled with Fluent NHibernate, seemed like the best choice to work with MySql.

It wasn’t long before I began to use the NHibernate Validator framework to provide some validation on my models. Using it is similar to Data Annotation Validators which I had used in another project and I liked the way you could use resource files to provide the error messages the Data Annotation Validators produce.

It seemed to take me ages to figure out the equivalent in the NHibernate Validator framework, as I had to piece it together from several other articles which talked about various customizations that could be done. In the end it turns out that its not very difficult to do at all. Here’s how:

Firstly, when validating your models, you need to point the validation engine to your resource file in the configuration:

//create engine
var engine =  new ValidatorEngine();
 
//configure and add resource file
var configure = new FluentConfiguration();
configure.SetCustomResourceManager("My.Website.Resources.ValidationMessages", Assembly.Load("MyWebsite"));
engine.Configure(configure);
 
//engine configured, now you can validate
var errors = engine.Validate(myentity);

To specifiy which resource value to use, you specify the resource key in the attribute wrapped in curly brackets as follows:

 
public class MyEntity {
 
  [NotNullNotEmpty(Message = "{ResourceKeyWithCurlyBrackets}")]
  public string SomeProperty { get; set; }
 
}

…and thats all there is to it, the text in the resource file should appear in the validation results.

 

One thought on “Using a Resource File for NHibernate Validation Messages

  1. Hi

    Nice find. Looks easy, but my tests for this are not resolving the curly braces…can you spot any mistake?

    I have Messages.resx (its all public) in MyProject.Core, using namespace MyProject.Resources

    NHValidator is setup:

    .SetCustomResourceManager(“MyProject.Resources.Messages”, Assembly.Load(“MyProject.Core”))

    And my model:

    public class LoginModel
    {
    [NotNullNotEmpty(Message = “{NotNullNotEmpty}”)]
    public string Username { get; set; }

    Error message returned is {NotNullNotEmpty}

    Checking the NHValidator configure object graph looks like the right bits are configured…any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *