简体   繁体   English

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

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

I'm testing a PUT with two string : 我用两个string测试PUT

company.CurrencyCode = request.CurrencyCode ?? company.CurrencyCode;
company.CountryIso2 = request.Country ?? company.CountryIso2;

and I tried with a rule like: 我尝试过如下规则:

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));
    });
}

as I don't mind to get a null on those properties, but I would like to test the Length when the property is not a null . 因为我不介意在这些属性上获取null ,但我想在属性不为null 测试Length

What is the best way to apply rules when a property is nullable and we just want to test if it's not null? 当属性可以为nullable时应用规则的最佳方法是什么,我们只想测试它是否为空?

One of the ways would be: 其中一种方式是:

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

I prefer the following syntax: 我更喜欢以下语法:

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

Best syntax for me: 对我来说最好的语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM