2022-08-22

FluentValidation ILanguageManager.GetString() not invoked for custom Rules

I have a custom rule like this:

public static IRuleBuilderOptionsConditions<T, string?> MustBeCool<T>(this IRuleBuilder<T, string?> ruleBuilder)
{
    return ruleBuilder.Custom((input, context) =>
    {
        if(/*input is not cools*/)
        {
            context.AddFailure("Not cool.");
        }
    });
}

I also have a custom implementation of the ILanguageManager which pulls translations for validation messages from a database. My custom LanguageManager works fine for built-in rules. My problem now is that the ILanguageManager.GetString(...) is not getting called for my custom rule. I guessed that this might be because there already is a valiation error message provided so I tried to add the failure like this:

context.AddFailure(new ValidationFailure
{
    PropertyName = context.PropertyName,
    ErrorCode = "MustBeCoolValidator"
    // no error message provided
});

That doesn't work either. An empty validation error message is returned. In my case the validation rules and the error message translations don't live in the same town so I can't really provide the translated validation error message where the rule is declared.

Is there a way to invoke the ILanguageManager.GetString() for my custom rule?



No comments:

Post a Comment