c# – 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}应该在一个公共位置,而不是在这里.但我不知道如何集中他们? >一种方法是使用所有这些常量字符串创建新的c#文件.这很简单. 解决方法
如果您需要更改内置规则的默认消息,这将影响包含此规则的所有验证程序 – 请执行以下步骤:
1:使用Startup.cs或global.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中用作属性名称. 2. Built in Validators – 在这里,您可以找到应在错误消息字符串中使用的所有验证规则的替换名称. 3. Messages.resx – 此处放置了错误消息的默认资源文件. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |