简体   繁体   中英

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 . When the field is empty, I get the following message:

"The field FieldName must be a number.".

The documentation says you should call WithMessage on a validator definition. 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.

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() .

The error your are receiving "The field FieldName must be a number." indicated that the value received is not a number while the property FieldName is a numeric type.

I have a problem with overriding the default error message when validating an InputNumber. When the field is empty, I get the following message:

Well, let's consider few things in regards of int . It shouldn't allow empty value if you define data-type as int . Thus, in case of InputNumber we have no logical ground for .NotEmpty() .

Logic: 1: Either, we should check if it is a null only when we would allow null value. 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. In this scenario we can do something like:

 .GreaterThan(0)
 .WithMessage("InputNumber must be greater than 0.");

Complete Scenario For An 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.");
              
                
                                                                   
        }
        
    }

Output: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM