如果字符串不为空,FluentValidation 如何检查长度?

FluentValidation how to check for Length if string is not null?

我正在用两个 string:

测试一个 PUT
company.CurrencyCode = request.CurrencyCode ?? company.CurrencyCode;
company.CountryIso2 = request.Country ?? company.CountryIso2;

我试过这样的规则:

public UpdateCompanyValidator()
{
    RuleSet(ApplyTo.Put, () =>
    {
        RuleFor(r => r.CountryIso2)
              .Length(2)
              .When(x => !x.Equals(null));

        RuleFor(r => r.CurrencyCode)
              .Length(3)
              .When(x => !x.Equals(null));
    });
}

因为我不介意在这些属性上获得 null,但我想测试 Length 属性 不是 null.

当 属性 是 nullable 并且我们只想测试它是否不为空时应用规则的最佳方式是什么?

其中一种方法是:

public class ModelValidation : AbstractValidator<Model>
{
    public ModelValidation()
    {
        RuleFor(x => x.Country).Must(x => x == null || x.Length >= 2);
    }
}

我更喜欢以下语法:

When(m => m.CountryIso2 != null,
     () => {
         RuleFor(m => m.CountryIso2)
             .Length(2);
     );

最适合我的语法:

RuleFor(t => t.DocumentName)
            .NotEmpty()
            .WithMessage("message")
            .DependentRules(() =>
                {
                    RuleFor(d2 => d2.DocumentName).MaximumLength(200)
                        .WithMessage(string.Format(stringLocalizer[""message""], 200));
                });