FluentValidation, how to check length if string is not null?

I am testing PUT with two string :

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

and I tried using 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)); }); } 

since I don't mind to get null for these properties, but I would like to check the Length when the property is not null .

What is the best way to apply the rules when the property is nullable and we just want to check if it is null?

+7
c # fluentvalidation
source share
2 answers

One of the methods:

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

I prefer the following syntax:

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

All Articles