[英]How to override the default error message for int using FluentValidation?
I have a problem with overriding the default error message when validating an InputNumber
.我在验证InputNumber
时遇到覆盖默认错误消息的问题。 When the field is empty, I get the following message:当该字段为空时,我收到以下消息:
"The field FieldName must be a number.". “字段 FieldName 必须是数字。”。
The documentation says you should call WithMessage
on a validator definition.该文档说您应该在验证器定义上调用WithMessage
。 I tried calling WithMessage
on NotEmpty
and NotNull
as shown below but it doesn't change the default message and I didn't see any other method that could check if the field is a number.我尝试在NotEmpty
和NotNull
上调用WithMessage
,如下所示,但它不会更改默认消息,而且我没有看到任何其他方法可以检查该字段是否为数字。
RuleFor(model => model.FieldName)
.NotEmpty()
.WithMessage("empty")
.NotNull()
.WithMessage("null");
Any help is much appreciated, thanks.非常感谢任何帮助,谢谢。
The messages specified with WithMessage()
are only used when the preceding validation fails, in your case NotEmpty()
and NotNull()
. WithMessage()
指定的消息仅在前面的验证失败时使用,在您的情况下为NotEmpty()
和NotNull()
。
The error your are receiving "The field FieldName must be a number."
您收到的错误"The field FieldName must be a number."
indicated that the value received is not a number while the property FieldName
is a numeric type.表示收到的值不是数字,而属性FieldName
是数字类型。
I have a problem with overriding the default error message when validating an InputNumber.我在验证 InputNumber 时遇到覆盖默认错误消息的问题。 When the field is empty, I get the following message:当该字段为空时,我收到以下消息:
Well, let's consider few things in regards of int
.好吧,让我们考虑一些关于int
的事情。 It shouldn't allow empty value if you define data-type as int
.如果您将数据类型定义为int
,则不应允许空值。 Thus, in case of InputNumber
we have no logical ground for .NotEmpty()
.因此,在InputNumber
的情况下,我们没有.NotEmpty()
的逻辑依据。
Logic: 1: Either, we should check if it is a null
only when we would allow null value.逻辑: 1:要么,只有当我们允许 null 值时,我们才应该检查它是否是null
。 For isntance:例如:
public int? InputNumber { get; set; }
So we can handle as below:所以我们可以如下处理:
.NotNull()
.WithMessage("Null Is not accepted")
Logic: 2: Or we can check if the InputNumber
is valid input.逻辑: 2:或者我们可以检查InputNumber
是否是有效输入。 In this scenario we can do something like:在这种情况下,我们可以这样做:
.GreaterThan(0)
.WithMessage("InputNumber must be greater than 0.");
Complete Scenario For An int? int 的完整场景? InputNumber:输入号码:
public class OverrideDefaultErrorMessageForInt : AbstractValidator<User>
{
public OverrideDefaultErrorMessageForInt()
{
RuleFor(x => x.InputNumber)
.NotNull()
.WithMessage("Null Is not accepted")
.GreaterThan(0)
.WithMessage("InputNumber must be greater than 0.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.