Denis
Denis

Reputation: 943

How to validate for null more than one properties by using FluentValidator?

Is there a way to validate for null more than one properties in a fluent manner?

For example, without using Fluentvalidator, this may be possible by implementing IValidatableObject.

    public class Request : IValidatableObject
    {
        public int Id { get; init; }

        public string Property1 { get; init; }
        public string Property2 { get; init; }
        public string Property3 { get; init; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Property1 == null && Property2 == null && Property3 == null)
            {
                yield return new ValidationResult("Some message");
            }
        }
    }

I found a way to use FluentValidator via override Validate, but this is not the way FluentValidator was created for.

    public class RequestValidator : AbstractValidator<Request>
    {
        public override FluentValidation.Results.ValidationResult Validate(ValidationContext<Request> context)
        {
            if (context.InstanceToValidate.Property1 is null &&
                context.InstanceToValidate.Property2 is null &&
                context.InstanceToValidate.Property3 is null)
            {
                return new FluentValidation.Results.ValidationResult(new[]
                {
                    new ValidationFailure("", "Custom message")
                });
            }
        
            return new FluentValidation.Results.ValidationResult();
        }
    }

Upvotes: 2

Views: 964

Answers (2)

David Liang
David Liang

Reputation: 21546

Another way/style to do it, which I found little more readable to me, is:

// I have nullable enabled

public class Request
{
    public int Id { get; init; }

    public string? Property1 { get; init; }
    public string? Property2 { get; init; }
    public string? Property3 { get; init; }
}

public class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        RuleFor(x => new List<string?> { x.Property1, x.Property2, x.Property3 })
            .Must(x => x.Any(x => x is not null))
            .WithMessage("You need to have at least one of Property 1, 2 or 3.");
    }
}

In the case where they're objects instead of primitive types, you can do something like

RuleFor(x => new List<object?> { x.Property1, x.Property2, ... })
    ...

Upvotes: 0

freakish
freakish

Reputation: 56587

One possible solution:

public class RequestValidator : AbstractValidator<Request>
{
    public RequestValidator()
    {
        RuleFor(x => x)
            .Must(
                x => x.Property1 is not null
                  || x.Property2 is not null
                  || x.Property3 is not null)
            .WithMessage("Custom message");
    }
}

Upvotes: 3

Related Questions