Search code examples
c#fluentvalidation

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();
        }
    }

Solution

  • 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");
        }
    }