标签: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}应该在一个公共位置,而不是在这里.但我不知道如何集中他们?
>一种方法是使用所有这些常量字符串创建新的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 – 此处放置了错误消息的默认资源文件.
标签:c,asp-net,localization,fluentvalidation 来源: https://codeday.me/bug/20190706/1394469.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。