gpt4 book ai didi

c# - 删除验证消息名称中的集合索引

转载 作者:行者123 更新时间:2023-11-30 17:26:07 24 4
gpt4 key购买 nike

我使用 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")
});
});

当我插入无效的电子邮件时,错误的名称是 "Emails[0]"

我想删除索引并简单地使用"Emails"

最佳答案

如果您想为您的消息添加电子邮件前缀,请在您的消息中使用“{PropertyValue}”:

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!")
});
});
}
}

输出:“emailexample.com:电子邮件无效!”

可以通过扩展为默认消息添加前缀(内置方法):

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

return ruleBuilderOptions;
}

用法:

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()
});
});
}
}

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

关于c# - 删除验证消息名称中的集合索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57208908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com