c# - FluentValidation 一个属性的多个错误消息

标签 c# asp.net-mvc asp.net-web-api fluentvalidation

我正在使用 FluentValidation 验证输入值。我正在使用一种方法来验证数据库中的值,该方法根据值返回整数值 -1、-2 和 -3 用于不同的错误消息。如何根据方法的返回值显示错误消息。我在类范围内创建了一个变量并设置了返回值,在下一条语句中我尝试比较并尝试显示消息,但我观察到下一条语句在更新值之前执行。

我想为一个输入值显示不同的错误消息。

例如用户输入一个负值错误消息应该是“不允许使用负值”, 如果用户输入了一个很大的数字,那么消息应该是“数字太长”。

这里是代码 ISValidAction 是验证输入并设置变量返回值的方法,此方法始终返回 true。

int returnvalue = 0;
RuleFor(r => r.action).Must(ISValidAction).WithMessage("Action does not exist in the system.").When(r => !String.IsNullOrEmpty(r.action));

RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -2 && returnvalue != -3)).WithMessage("");//for -1
        RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -1 && returnvalue != -3)).WithMessage("");//for -2
        RuleFor(r => returnvalue).Must(r => !(returnvalue != 1 && returnvalue != -1 && returnvalue != -2)).WithMessage("");// for -3

最佳答案

我得到了解决方案!用于针对一个值显示多个错误。

我刚刚在 PropertyValidatorContext 中添加了错误消息

RuleFor(r => r.action).Must(ActionRateLimit).When(r => !String.IsNullOrEmpty(r.action));

这是使用函数进行验证的调用。

这是方法。

private bool ActionRateLimit(LogActionInput obj, string actionName, PropertyValidatorContext context)
        {
        int result = 0;
        IRecognitionStoreService StoreService = new RecognitionStoreService();
        result = StoreService.ActionRateLimit(actionName, obj.userName);            
        if (result==1)
        {
           return true;
        }
        else if (result==0)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage","Invalid action name or the user doesn't exists.");
        }
        else if(result==-1)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage", "Action exceeds its rate limit. Please try again in a while.");
        }
        else if (result == -3)
        {
            context.MessageFormatter.AppendArgument("ValidationMessage", "This user has not completed the prequisite challenge. Action logging failed.");
        }
        return false;

        }

    }

它工作正常。

关于c# - FluentValidation 一个属性的多个错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620454/

相关文章:

c# - 在程序运行时读取控制台输出 C#

c# - 企业代理适用于 C#,但不适用于 Python

c# - MySqlConnection 不工作

c# - Request.Url.AbsoluteUri 在 asp.net core 2.0 中不起作用(使用 System.Web)

asp.net-mvc - 以表单上传图像并在 MVC 4 上显示

asp.net-web-api - 如何在 Web Api 调用期间获取用户上下文?

c# - Umbraco 媒体服务创建媒体

c# - asp.net web api - 模型绑定(bind)列表参数

c# - 从 MVC 项目中删除 Entity Framework 引用

mysql - 查询返回 "The method or operation is not implemented."错误