我正在使用 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/