21

I'm testing a PUT with two string:

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.

What is the best way to apply rules when a property is nullable and we just want to test if it's not null?

balexandre
  • 73,608
  • 45
  • 233
  • 342

3 Answers3

24

One of the ways would be:

public class ModelValidation : AbstractValidator<Model>
{
    public ModelValidation()
    {
        RuleFor(x => x.Country).Must(x => x == null || x.Length >= 2);
    }
}
Michal Dymel
  • 4,312
  • 3
  • 23
  • 32
21

I prefer the following syntax:

When(m => m.CountryIso2 != null,
     () => {
         RuleFor(m => m.CountryIso2)
             .Length(2);
     );
StoriKnow
  • 5,738
  • 6
  • 37
  • 46
3

Best syntax for me:

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