FluentValidation: How do i put all validation mess

2019-06-25 14:14发布

问题:

This is one of my validation class:

public class StocksValidator : AbstractValidator<Stocks>
    {
        public StocksValidator()
        {
            RuleFor(x => x.SellerId).GreaterThan(1).WithMessage("SellerId should be greater than 1")
                                    .LessThan(100).WithMessage("SellerId should be less than 100");
            RuleFor(x => x.SellerType).GreaterThan(101).WithMessage("SellerType should be greater than 101")
                                    .LessThan(200).WithMessage("SellerType should be less than 200");
            RuleFor(x => x.SourceId).GreaterThan(201).WithMessage("SourceId should be greater than 201")
                                    .LessThan(300).WithMessage("SourceId should be less than 300");
        }
    }

I understand that these messages like {field} should be less that {x} should be at a common location and not here. But i don't have a clue how to centralize them?

  1. One way could be to create new c# file with all these constant strings. This is fairly simple.

  2. Using localization in web api with fluent validation. What are benefits of this. Where do i find its good tutorial?

回答1:

If you need to change default messages for built-in rule(s), that will affect all validators, which contain this rule(s) — follow next steps:

1: set up fluent validation with your custom resource provider class at Startup.cs or global.asax.cs

ValidatorOptions.ResourceProviderType = typeof(MyResourceProvider);

2: override default messages for some validation rules

// create MyResourceProvider.resx to auto-generate this class in MyResourceProvider.Designer.cs file (support multiple cultures out of box),
// or create class manually and specify messages in code
public class MyResourceProvider {
   public static string greaterthan_error {
      get { 
          return "{PropertyName} should be greater than {ComparisonValue}, but you entered {PropertyValue}";
      }
   }
   public static string lessthan_error {
      get { 
          return "{PropertyName} should be less than {ComparisonValue}";
      }
   }
}

3 (optional): use WithName() method to replace default output of property name with more user-friendly

RuleFor(x => x.SellerId).GreaterThan(1).WithName("Seller identidier") 
// outputs "Seller identidier should be greater than 1, but you entered 0"

More information you can find at FluentValidation github:

1. Localization — here you can find more info about ways to localize messages (like WithLocalizedMessage method), and also resource names, that should be used as property names in MyResourceProvider.

2. Built in Validators - here you can find substitution names for all validation rules, that should be used in error message strings.

3. Messages.resx - default resource file with error messages placed here.