如何为FluentValidation中不可修改的扩展方法设置自定义错误信息
方案1:重写验证器的PreValidate方法(最推荐,仅当前验证器生效,无全局污染)
你可以在当前Validator类中重写PreValidate方法,在验证结果返回前直接匹配并替换目标错误信息,不会影响全局其他验证逻辑:
public class Validator : AbstractValidator<Command> { public Validator(ICheckExists<ICheckEntityExists> checkEntityExists) { RuleFor(x => x) .EntityDoesNotExist(checkEntityExists, c => new CheckEntityExists() { TypeId = c.Id, StatusId = c.StatusId }); } protected override bool PreValidate(ValidationContext<Command> context, ValidationResult result) { var basePass = base.PreValidate(context, result); if (!basePass) return false; // 匹配目标错误并替换 foreach (var error in result.Errors.Where(e => e.ErrorMessage == "must not exist")) { error.ErrorMessage = "你需要的自定义错误提示"; // 还可按需修改PropertyName等属性 // error.PropertyName = "自定义属性名"; } return true; } }
如果担心匹配文本不稳定,可先调试拿到EntityDoesNotExist生成错误对应的ErrorCode,通过ErrorCode匹配准确度更高。
方案2:使用OnFailure回调(侵入性最低)
EntityDoesNotExist作为FluentValidation的规则扩展,返回的规则实例默认支持OnFailure回调,可以在触发错误时直接修改错误信息:
RuleFor(x => x) .EntityDoesNotExist(checkEntityExists, c => new CheckEntityExists() { TypeId = c.Id, StatusId = c.StatusId }) .OnFailure((ctx, error) => { error.ErrorMessage = "自定义错误提示"; });
方案3:封装自定义扩展方法(适合多场景复用)
如果多个验证器都需要用到EntityDoesNotExist并自定义提示,可以封装一层自定义扩展方法,后续直接调用即可:
public static class CustomValidationExtensions { public static IRuleBuilderOptions<T, TProperty> EntityDoesNotExistWithMsg<T, TProperty>( this IRuleBuilder<T, TProperty> ruleBuilder, ICheckExists<ICheckEntityExists> checkEntityExists, Func<T, CheckEntityExists> entityFactory, string errorMsg = "自定义默认提示") { return ruleBuilder .EntityDoesNotExist(checkEntityExists, entityFactory) .OnFailure((_, error) => error.ErrorMessage = errorMsg); } } // 调用示例 RuleFor(x => x) .EntityDoesNotExistWithMsg(checkEntityExists, c => new CheckEntityExists() { TypeId = c.Id, StatusId = c.StatusId }, "该组合数据已存在");
内容的提问来源于stack exchange,提问作者RheinmetallSkorpion
相关产品推荐
相关产品推荐

