一个 Fluent Validation 规则中的条件和非条件

Conditional and non-conditional in one Fluent Validation rule

我需要验证邮政编码, - 它总是必须有一个值(非条件)

// General Rule:
RuleFor( m => m.Zip ).NotEmpty()
    .WithMessage( "Zip code is required." );

如果在美国,值应匹配正则表达式(有条件)

// United States Rule:
RuleFor( m => m.Zip )
    .Matches( ZipCodeRegEx )
    .WithMessage( "Invalid Zip Code" )
    .When( m => IsUnitedStates( m.CountryCode ) );

我的目标是将一般规则和美国规则合并为一个规则 , 我试过:

// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );

// doesn't check general rule for non-us
RuleFor( m => m.Zip )
    .NotEmpty()
        .When( m => true )// always
        .WithMessage( "Zip code is required." )
    .Matches( ZipCodeRegEx )
        .When( m => IsUnitedStates( m.CountryCode ) )
        .WithMessage( "Invalid Zip Code" );

如何在一个规则中写这个?

不可能在一个规则中做到这一点。 FluentValidation 并非旨在支持这种情况。