Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Collection Index in Validation Message Name

I have the following validation using FluentValidation 8:

RuleFor(x => x.Emails)
    .NotNull()
    .ForEach(x => {
        x.SetValidator(y => new InlineValidator<String>
        {
            z => z.RuleFor(u => u).EmailAddress().WithMessage("Email is invalid")
        });
    });

When I insert an invalid email the name of the error is "Emails[0]".

I would like to remove the index and simply use "Emails".

like image 783
Miguel Moura Avatar asked Jan 25 '26 20:01

Miguel Moura


1 Answers

If you want to add email prefix to your message use "{PropertyValue}" to your message:

public class ModelValidator : AbstractValidator<Model>
{
    public ModelValidator()
    {
        RuleFor(x => x.Emails)
            .NotNull()
            .ForEach(x =>
            {
                x.SetValidator(y => new InlineValidator<string>()
                {
                    z => z.RuleFor(u => u)
                    .EmailAddress()
                    .WithMessage("{PropertyValue} : Email is invalid!")
                });
            });
    }
}

Output: "emailexample.com : Email is invalid!"

Adding prefix to default messages (built-in methods) can be done through extension:

public static IRuleBuilderOptions<string, string> AddMessagePrefix(
    this IRuleBuilderOptions<string, string> ruleBuilderOptions)
{
    ruleBuilderOptions.Configure(configurator =>
    {
        configurator.MessageBuilder = ctx =>
        {
            return $"{ctx.Instance}: {ctx.GetDefaultMessage()}";
        };
    });

    return ruleBuilderOptions;
}

Usage:

public class ModelValidator : AbstractValidator<Model>
{
    public ModelValidator()
    {
        RuleFor(x => x.Emails)
            .NotNull()
            .ForEach(x =>
            {
                x.SetValidator(y => new InlineValidator<string>()
                {
                    z => z.RuleFor(u => u)
                    .EmailAddress()
                    .AddMessagePrefix()
                });
            });
    }
}

Output : "emailexample.com: '' неверный email адрес."

like image 180
HelloWorld Avatar answered Jan 27 '26 08:01

HelloWorld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!