在自定义验证上设置自定义消息

在自定义验证上设置自定义消息

本文介绍了流利的验证:在自定义验证上设置自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景

我有一个自定义规则来验证订单的运费:

I have a custom rule to validate the shipping cost of an order:

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

如果发生异常,我会将异常信息存储到

In case of exception, I store the exception info into the CustomInfo private member and I add it to the validation message.

然后我运行验证器:

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,而只会显示消息的第一部分:

Everything works right, in case of exception the CustomInfo is properly set to the ex.ToString() value. But eventually the error message displayed in the console does NOT show the CustomInfo, but only the first part of the message:

      "Shipping Cost not set or not correct: 5.9"

问题

为什么自定义消息不包含CustomInfo字符串?
是否可以通过另一种方式在自定义消息中添加异常信息?

Why the custom message does not contains the CustomInfo string?Is it possible to add the exception info the the custom message in another way?

推荐答案

根据此

您应该使用

.WithMessage("{PropertyName} not set or not correct: {PropertyValue}. {0}", order => order.CustomInfo);

这将要求您的CustomInfo位于Order类的级别,而不是验证器类

which would require that your CustomInfo on the level of the Order class, rather than your validator class

编辑

您可以使用:

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];
    }
}

对验证器进行一些小的更改

with some small changes to your validator

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

这篇关于流利的验证:在自定义验证上设置自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:16