FluentValidation:如何将所有验证消息放在一个位置?

时间:2016-08-02 10:16:44

标签: c# asp.net localization fluentvalidation

这是我的验证课程之一:

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");
        }
    }

我理解像{field}这样的消息应该少于{x}应该在一个公共位置,而不是在这里。但我不知道如何集中他们?

  1. 一种方法是使用所有这些常量字符串创建新的c#文件。这很简单。

  2. 在网络API中使用本地化,流畅的验证。这有什么好处。我在哪里找到它的好教程?

1 个答案:

答案 0 :(得分:1)

如果您需要更改内置规则的默认消息,将影响包含此规则的所有验证程序,请执行以下步骤:

1 :使用Startup.csglobal.asax.cs

上的自定义资源提供程序类设置流畅的验证
ValidatorOptions.ResourceProviderType = typeof(MyResourceProvider);

2 :覆盖某些验证规则的默认消息

// 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(可选):使用WithName()方法将属性名称的默认输出替换为更加用户友好的

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

您可以在FluentValidation github找到更多信息:

1. Localization - 在这里,您可以找到有关本地化消息的方法(如WithLocalizedMessage方法)以及资源名称的更多信息,这些信息应在MyResourceProvider中用作属性名称。< / p>

2. Built in Validators - 在这里,您可以找到所有验证规则的替换名称,该名称应在错误消息字符串中使用。

3. Messages.resx - 此处放置错误消息的默认资源文件。