Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Localized Message Issue

$
0
0
Hi

So the WithLocalizedMessage that you're using doesn't actually take a real lambda - it is literally only used to specify a resource type and resource name, using the standard resex files eg:
WithLocalizedMessage(() => MyResources.SomeMessage) 
...it basically just uses the type name and the property name to find a resource called "SomeMessage" in a resource file called "MyResources" - it doesn't actually ever invoke this lambda.

What you'll need to do is provide an implementation of IStringSource that can read from your cache. IStringSource is FluentValidation's abstraction for providing an error message or property name. The standard implementations are to use a constant string (ie just a call to WithMessage("some message"), as implemented in StaticStringSource.cs) or a localized string based on a resource type and name (LocalizedStringSource.cs). Something like this should work:
public class MyStringSource : IStringSource {
  private string _resourceName;
  public MyStringSource(string name) { 
    _resourceName = name;
  }

  public string GetString() {
    return DisplayResource.GetResourceValue(_resourceName);
  }
  
  // no-op. 
  public string ResourceName { get { return null; } }
  public Type ResourceType { get { return null; } }
}
Then to use it, you'd need to acces the underlying rule configuration:
RuleFor(x => x.Name).NotNull().Configure(cfg => {
   cfg.CurrentValidator.ErrorMessageSource = new MyStringSource("my resource name");
});
That's a bit long winded, so I'd wrap it an extension method:
public static class MyExtensions {
   //todo: give better name!
   public static IRuleBuilderOptions<T, TProperty> MyLocalizeMethod<T,TProperty>(this IRuleBuilder<T, TProperty> rule, string resourceName) {
      return rule.Configure(cfg => {
          cfg.CurrentValidator.ErrorMessageSource = new MyStringSource(resourceName);
      });
   }
}
...which you can then use like this:
RuleFor(x => x.Name).NotNull().MyLocalizeMethod("foo");
Hope this helps.

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>