- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
场景
我有一个自定义规则来验证订单的运费:
public class OrderValidator : BaseValidator<Order>
{
private string CustomInfo { get; set; }
public OrderValidator()
{
//here I call the custom validation method and I try to add the CustomInfo string in the message
RuleFor(order => order.ShippingCost).Cascade(CascadeMode.StopOnFirstFailure).NotNull().Must(
(order, shippingCost) => CheckOrderShippingCost(order, shippingCost)
).WithMessage("{PropertyName} not set or not correct: {PropertyValue}." + (String.IsNullOrEmpty(CustomInfo) ? "" : " " + CustomInfo));
}
//this is the custom validation method
private bool CheckOrderShippingCost(Order o, decimal shippingCost)
{
bool res = false;
try
{
/*
* check the actual shippingCost and set the res value
*/
}
catch (Exception ex)
{
CustomInfo = ex.ToString();
res = false;
}
return res;
}
}
如果出现异常,我将异常信息存储到 CustomInfo 私有(private)成员中,并将其添加到验证消息中。
然后我运行验证器:
OrderValidator oVal = new OrderValidator();
oVal.Results = oVal.Validate(order);
if (!oVal.Results.IsValid)
oVal.Results.Errors.ForEach(delegate(ValidationFailure error) {
Console.WriteLine(error.ErrorMessage);
});
问题
一切正常,在异常情况下 CustomInfo 被正确设置为 ex.ToString() 值。但最终显示在控制台中的错误消息并没有显示 CustomInfo,而是只显示了消息的第一部分:
"Shipping Cost not set or not correct: 5.9"
问题
为什么自定义消息不包含CustomInfo字符串?是否可以通过其他方式将异常信息添加到自定义消息中?
最佳答案
你应该使用
.WithMessage("{PropertyName} not set or not correct: {PropertyValue}. {0}", order => order.CustomInfo);
这将要求您的 CustomInfo 在 Order 类级别,而不是您的验证器类
编辑
你可以使用:
public static class OrderExtensions
{
private static IDictionary<Order,string> customErrorMessages;
public static void SetError(this Order order, string message) {
if (customErrorMessages == null) {
customErrorMessages = new Dictionary<Order,string>();
}
if (customErrorMessages.ContainsKey(order)) {
customErrorMessages[order] = message;
return;
}
customErrorMessages.Add(order, message);
}
public static string GetError(this Order order) {
if (customErrorMessages == null || !customErrorMessages.ContainsKey(order)) {
return string.Empty;
}
return customErrorMessages[order];
}
}
对您的验证器进行一些小改动
public class OrderValidator : BaseValidator<Order>
{
public OrderValidator()
{
//here I call the custom validation method and I try to add the CustomInfo string in the message
RuleFor(order => order.ShippingCost).Cascade(CascadeMode.StopOnFirstFailure).NotNull().Must(
(order, shippingCost) => CheckOrderShippingCost(order, shippingCost)
).WithMessage("{PropertyName} not set or not correct: {PropertyValue}. {0}", order => order.GetError()));
}
//this is the custom validation method
private bool CheckOrderShippingCost(Order o, decimal shippingCost)
{
bool res = false;
try
{
/*
* check the actual shippingCost and set the res value
*/
}
catch (Exception ex)
{
order.SetError(ex.ToString());
res = false;
}
return res;
}
}
关于c# - 流利验证 : set custom message on custom validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135658/
当我尝试输入时,我正在关注 Ray Wenderlich ( https://videos.raywenderlich.com/screencasts/545-server-side-swift-wi
我正在使用 javax.validation.Validation 来验证 jpa 实体。我总是针对相同的实体进行验证。 我想知道是对所有验证使用一个 validator 更好,还是每次验证时实例化一
Controller : @RequestMapping(...) public void foo(@Valid Parent p){ } class Parent { @NotNull // j
在 login.phtml 中,validator 和 validate 之间有什么区别 - 有人可以解释下面每一行的含义 function onepageLogin(button)
我有一个 java bean 用于将 JSON 消息发送到 spring @RestController 并且我有 bean 验证设置并使用 @Valid 运行得很好。但我想转移到 Protobuf/
我正在使用 vee-validate 来验证注册表单,我编写了如下代码,
使用 有什么区别属性和 标签? 我应该什么时候使用哪一种? 最佳答案 validator属性允许您引用独立的托管 bean 方法,而不仅仅是像这样的验证器
我们有这个 Alamofire 错误处理: Alamofire.request(.GET, getUrl("mystuff")).responseData { response in guar
以下代码创建了两个单选按钮。每个选项都包含一个日期值,该日期值已成功转换为格式为“yyyy-MM-dd”的标签。一旦我做出选择并单击下一步按钮,我就会收到以下错误“j_idt12:comDateCho
是否有类似的验证: req.checkBody('property', 'should be present').isPresent(); 值本身并不重要。 现在我使用这个解决方案: .isLengt
系列文章: 1、async-validator 源码学习(一):文档翻译 2、async-validator 源码学习笔记(二):目录结构 3、async-validator 源码学习笔记(三):ru
我正在使用 Backbone.Validation插入。我有一个模型可以在服务器端进行唯一性检查。我如何让 backbone.validation 识别错误并运行我设置的回调以显示返回的错误消息? t
我有一个 Knockout.Validation 场景,我认为该场景相当普遍,但尚未通过在网络上搜索和本网站上的各种答案找到解决方案。 我正在验证的属性在 ajax 调用之后才会添加到可观察到的 kn
我是 Knockout JS 的新手。我需要一个验证器来验证用户将在文本框中输入的日期。为此编写了如下代码 ko.validation.rules['date'] = { validator:
如何在 JSF 验证器中比较两个字符串是否相等? if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword()
我有简单的域: package app class Customers { String CUSTOMER String NOTE static mapping = {
我正在使用 ember-validations 来验证表单中的模型。 如果我使用 createRecord 创建记录,则模型的实例已经过验证,因此在用户输入值之前表单已经显示验证错误。 我只想在提交表
我有两种不同的服务:第一个是将对象保存到数据库,第二个是更新现有对象。 我正在对我的对象使用验证约束,例如(@NotBlank、@Size、@Pattern 等),在第一种情况下,我需要验证对象的所有
我有 2 个 ensure - 验证装饰器用于 2 个字段:password 和 retypePassword。我想在填写 retypePassword 字段时检查这两个字段是否相等。 问题是,当我在
I'm aware that it's a bug ,但是在域类上调用 validate() 会覆盖之前放入的任何拒绝: def save = { def assignment = new A
我是一名优秀的程序员,十分优秀!