Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation: How do i put all validation messages at a single location?

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?

like image 466
Sahil Sharma Avatar asked Aug 02 '16 10:08

Sahil Sharma


People also ask

How Fluent validation works?

Fluent Validation is a free to use . NET validation library that helps you make your validations clean, easy to create, and maintain. It even works on external models that you don't have access to, with ease. With this library, you can separate the model classes from the validation logic like it is supposed to be.

What is Fluent validation c#?

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.

Should I use fluent validation?

Summary. FluentValidation provides a great alternative to Data Annotations in order to validate models. It gives better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.


1 Answers

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.

like image 177
Evgeny Levin Avatar answered Oct 12 '22 02:10

Evgeny Levin