fluent validation custom message and errorcode

Viewed 2610

i'm using fluent validation (both 9 and 10 now..) to request validation in asp.net core 5 web application, i'm having some issues with custom messages and error codes...

public class FooRequest
{
    public string foo1 { get; set; }
    public string foo2 { get; set; }
}

public class FooValidator :  AbstractValidator<FooRequest>
{
    public FooValidator() : base()
    {
        RuleFor(r => r.foo1)
            .NotEmpty()
            .WithMessage($"my message 1")
            .WithErrorCode("MY_ERROR_CODE_1"); 
    }
}

//controller's action with DI
[HttpPost("fooValidator")]
public void fooValidator([FromBody] FooRequest fooRequest)
{
}

but i receive and unexpected response (without custom errorCode, and with customMessage inside the errorCode), where i'm wrong??

{
    "message": "Bad Request",
    "errorCode": "my message 1"
}

P.S. if i change the validator, to set just customErorr

RuleFor(r => r.foo1)
    .NotEmpty()
    .WithErrorCode("MY_ERROR_CODE_1"); 

i receive the default one:

{
    "message": "Bad Request",
    "errorCode": "'foo1' must not be empty."
}

P.S.2 if i try to set the customMessage:

RuleFor(r => r.foo1)
    .NotEmpty()
    //.WithErrorCode("MY_ERROR_CODE_1")
    .WithMessage("my error message 1");

i receive the default message, with errorCode

{
    "message": "Bad Request",
    "errorCode": "my error message 1"
}
1 Answers

This is expected behavior with FluentValidation. The WithErrorCode(string) method is used for localizing error messages — internationalization (I18n). It is not meant to return an error code to the client.

From the FluentValidation documentation:

ErrorCode and Error Messages

The ErrorCode is also used to determine the default error message for a particular validator. At a high level:

  • The error code is used as the lookup key for an error message. For example, a NotNull() validator has a default error code of NotNullValidator, which used to look up the error messages from the LanguageManager. See the documentation on localization.
  • If you provide an error code, you could also provide a localized message with the name of that error code to create a custom message.
  • If you provide an error code but no custom message, the message will fall back to the default message for that validator. You’re not required to add a custom message.
  • Using ErrorCode can also be used to override the default error message. For example, if you use a custom Must() validator, but you’d like to reuse the NotNull() validator’s default error message, you can call WithErrorCode("NotNullValidator") to achieve this result.

(emphasis, mine)

Related