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".
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 адрес."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With