You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用FluentValidation为所有字符串属性配置全局校验规则

实现结论

可以通过FluentValidation实现针对所有字符串属性的全局校验,禁止取值以「=」开头,以下是两种常用实现方案:

方案1:全局无侵入配置(推荐,所有Validator自动生效)

在程序启动入口(如ASP.NET Core的Program.cs)添加全局规则配置即可,无需修改现有业务校验类:

using FluentValidation;

ValidatorOptions.Global.ApplyToAllRuleBuilders = (ruleBuilder, rule) =>
{
    // 仅对字符串类型的属性追加校验规则
    if (rule.TypeToValidate != typeof(string)) return;

    ruleBuilder.Must(value =>
    {
        var str = value as string;
        // 空值、空字符串不触发该规则,可根据业务需求调整
        return string.IsNullOrWhiteSpace(str) || !str.StartsWith('=');
    })
    .WithMessage("属性 {PropertyName} 不能以「=」字符开头");
};

方案2:自定义Validator基类(按需生效,可指定部分校验类使用)

如果不需要全量校验器都应用该规则,可以自定义基类校验器,业务校验类继承该基类即可生效:

using FluentValidation;
using System.Reflection;

public abstract class CustomBaseValidator<T> : AbstractValidator<T>
{
    protected CustomBaseValidator()
    {
        // 遍历当前校验模型所有字符串属性,自动追加规则
        var stringProps = typeof(T).GetProperties()
            .Where(p => p.PropertyType == typeof(string));

        foreach (var prop in stringProps)
        {
            RuleFor(prop.Name)
                .Must(value =>
                {
                    var str = value as string;
                    return string.IsNullOrWhiteSpace(str) || !str.StartsWith('=');
                })
                .WithMessage($"属性 {prop.Name} 不能以「=」字符开头");
        }
    }
}

// 业务校验类继承基类即可自动应用规则
public class BusinessDtoValidator : CustomBaseValidator<BusinessDto>
{
    public BusinessDtoValidator()
    {
        // 此处只需添加业务特有校验规则即可
        RuleFor(x => x.UserName).NotEmpty().MaximumLength(20);
    }
}

特殊场景说明

如果某部分字符串属性需要跳过该规则,可在对应校验规则后追加.Unless()条件过滤,或者在全局配置中增加自定义标记判断逻辑即可。


内容的提问来源于stack exchange,提问作者harishr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:15:03