Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 474
balexandre Avatar asked Jul 27 '15 14:07

balexandre


People also ask

How do you debug fluent validation?

There is no way to debug Fluent Validator code with Visual Studio tools. You need to comment the specific part of code (RuleFor) that you want to test. Keep doing it until all rules are tested.

What is fluent validation?

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.

Is fluent validation open source?

FluentValidation is an open source validation library for . NET. It supports a fluent API, and leverages lambda expressions to build validation rules.


3 Answers

One of the ways would be:

public class ModelValidation : AbstractValidator<Model>
{
    public ModelValidation()
    {
        RuleFor(x => x.Country).Must(x => x == null || x.Length >= 2);
    }
}
like image 186
Michal Dymel Avatar answered Sep 27 '22 23:09

Michal Dymel


I prefer the following syntax:

When(m => m.CountryIso2 != null,
     () => {
         RuleFor(m => m.CountryIso2)
             .Length(2);
     );
like image 35
StoriKnow Avatar answered Sep 27 '22 21:09

StoriKnow


Best syntax for me:

RuleFor(t => t.DocumentName)
            .NotEmpty()
            .WithMessage("message")
            .DependentRules(() =>
                {
                    RuleFor(d2 => d2.DocumentName).MaximumLength(200)
                        .WithMessage(string.Format(stringLocalizer[""message""], 200));
                });
like image 30
Aleh Avatar answered Sep 27 '22 23:09

Aleh