这是我的验证课程之一:
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#文件.这很简单.
>在web api中使用本地化,具有流畅的验证.这有什么好处.我在哪里找到它的好教程?
解决方法
如果您需要更改内置规则的默认消息,这将影响包含此规则的所有验证程序 – 请执行以下步骤:
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 – 此处放置了错误消息的默认资源文件.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。