Home > OS >  How to override the default error message for int using FluentValidation?
How to override the default error message for int using FluentValidation?

Time:01-07

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.

CodePudding user response:

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.

CodePudding user response:

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: enter image description here

  • Related