You need to enable JavaScript to run this app. FluentValidation 9.2.2 如何跳过未传入父字段的子字段校验规则?
优惠活动
大模型
产品
解决方案
定价
更多

FluentValidation 9.2.2 如何跳过未传入父字段的子字段校验规则?

FluentValidation 9.2.2 空引用异常配置指南

问题场景

使用FluentValidation 9.2.2版本时,校验流程触发System.NullReferenceException: 'Object reference not set to an instance of an object.'异常。

正常携带geographyInfo字段的合法入参示例:

{ "geographyInfo": { "CountryCode": "UK" } }

当前配置的校验规则代码:

RuleFor(x => x.Request.GeographyInfo)
    .NotEmpty()
    .WithMessage("GeographyInfo missing. Expected: object of type GeoInfo.")
    .WithErrorCode("123")
    .WithName("geographyInfo");

RuleFor(x => x.Request.GeographyInfo.CountryCode)
    .NotEmpty()
    .WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
    .WithErrorCode("13")
    .WithName("countryCode");

当入参为不携带geographyInfo字段的空结构时:

{ }

预期返回「GeographyInfo missing. Expected: object of type GeoInfo.」的规则提示,实际却触发空引用。根因是FluentValidation会并行执行所有配置的校验规则,此时Request.GeographyInfo本身为null,第二条规则直接访问其下的CountryCode属性,触发空引用。

适配方案

以下方案均可在不升级版本的前提下,实现“父字段未传入时跳过其子字段校验”的需求:

  • 方案1:通过When条件包裹子属性校验逻辑
    给CountryCode的校验规则增加前置判断,仅当GeographyInfo不为空时才执行该条校验。改写后代码如下:

    // 父对象校验规则保持原有逻辑不变
    RuleFor(x => x.Request.GeographyInfo)
        .NotEmpty()
        .WithMessage("GeographyInfo missing. Expected: object of type GeoInfo.")
        .WithErrorCode("123")
        .WithName("geographyInfo");
    
    // 用When条件包裹子属性校验,仅在父对象非空时执行
    When(x => x.Request.GeographyInfo != null, () =>
    {
        RuleFor(x => x.Request.GeographyInfo.CountryCode)
            .NotEmpty()
            .WithMessage("Field geographyInfo.CountryCode is missing. Expected: 3 digit code")
            .WithErrorCode("13")
            .WithName("countryCode");
    });
    

    配置完成后,当GeographyInfo为null时,框架会直接跳过子属性校验,仅触发父对象的NotEmpty规则返回对应提示,不会触发空引用。

  • 方案2:通过Cascade配置调整规则执行中断逻辑
    在父对象的校验链上配置级联中断规则,当父对象校验不通过时,中断当前规则链后续的校验动作。示例代码:

    RuleFor(x => x.Request.GeographyInfo)
        .Cascade(CascadeMode.Stop)
        .NotEmpty()
        .WithMessage("GeographyInfo missing. Expected: object of type GeoInfo.")
        .WithErrorCode("123")
        .WithName("geographyInfo");
    

    注意:该配置的作用范围仅为当前规则链,由于当前业务中针对CountryCode的校验是独立定义的规则,因此该方案无法覆盖当前跨规则的空引用场景,仅适合同个属性链下的连续校验优化。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 01:24:04