balexandre balexandre - 1 year ago 129
C# Question

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

I'm testing a

with two

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)
.When(x => !x.Equals(null));

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

as I don't mind to get a
on those properties, but I would like to test the
when the property is not a

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

Answer Source

One of the ways would be:

public class ModelValidation : AbstractValidator<Model>
    public ModelValidation()
        RuleFor(x => x.Country).Must(x => x == null || x.Length >= 2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download