Complex model validation using Fluent Validation

Full source code is available here.

A common problem is validating an object using a complicated set of rules.

I started using the Fluent Validation package some time back, it is commonly used with MVC and Web API applications but can be used with in any scenario that requires validation. It allows you to easily and quickly build flexible validation rules.

Of course it is possible to apply basic data annotations or build a custom validation attribute.

But out of the box Fluent Validation offers much more elaborate validators like, CreditCard, EmailAddress ExclusiveBetween and many more. It also has a Must validator that takes a predicate you define. This allows the creation of any complex rule.

For example, the validator can check that the person create request (shown below) has at least one active primary phone and at least one active primary email.

Fluent Validation can also be easily used in a console app, with data annotations you would have to jump through hoops to get validation working.

  public class PersonCreateRequestValidator : AbstractValidator<PersonCreateRequest>
        public PersonCreateRequestValidator()
            RuleFor(r => r.Firstname).NotEmpty();
            RuleFor(r => r.Lastname).NotEmpty();

            RuleFor(r => r.Addresses).NotNull();
            RuleFor(r => r.Addresses).NotEmpty();

            RuleFor(r => r.Addresses).Must(HaveAnActiveAndPrimary).WithMessage("One (and only one) address must be primary and active");
            RuleFor(r => r.Phones).Must(HaveAnActiveAndPrimary).WithMessage("One (and only one) phone must be primary and active");

        private bool HaveAnActiveAndPrimary(IEnumerable<IActivePrimary> items)
            if (items == null)
                return false;

            int activePrimary = items.Count(p => p.IsActive && p.IsPrimary);
            return (activePrimary == 1);

This a simple example of usage –

            var personCreateRequest = new PersonCreateRequest
                PersonId = Guid.NewGuid(),
                Firstname = "Tom",
                Lastname = "Travers",
                Addresses = new List<Address>() { new Address { Street = "Main", IsActive = true, IsPrimary = false, }, new Address{Street = "Boylston", IsActive = true, IsPrimary = true} },
                Phones = new List<Phone>() { new Phone { PhoneNumber = "124",  IsActive = true, IsPrimary = false } }

            var validator = new PersonCreateRequestValidator();
            ValidationResult result = validator.Validate(personCreateRequest);

Validating against multiple parts of the request

If you have the slightly more complicated scenario where you need either an active and primary phone or an active and primary address, add the following predicate –

        private bool AtLeastOneActiveAndPrimaryBetweenPhoneAndAddress(PersonCreateRequest p)
            bool addressActiveAndPrimary = HaveAnActiveAndPrimary(p.Addresses);
            bool phoneActiveAndPrimary = HaveAnActiveAndPrimary(p.Phones);

            bool result = addressActiveAndPrimary || phoneActiveAndPrimary;

            return result;

And call it like so –

        public PersonCreateRequestValidator()
            RuleFor(r => r).Must(AtLeastOneActiveAndPrimaryBetweenPhoneAndAddress).WithName("request");

Of course you can’t now call Must(HaveAnActiveAndPrimary) on just the phones and addresses.


  public class PersonCreateRequest
        public Guid RequestId { get; set; }
        public Guid PersonId { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public List<Address> Addresses { get; set; }
        public List<Phone> Phones { get; set; }


    public class Address : IActivePrimary
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public bool IsPrimary { get; set; }
        public bool IsActive { get; set; }


    public class Phone : IActivePrimary
        public string PhoneNumber { get; set; }
        public bool IsPrimary { get; set; }
        public bool IsActive { get; set; }


    public interface IActivePrimary
        bool IsPrimary { get; set; }
        bool IsActive { get; set; }

Full source code is available here.

2 thoughts on “Complex model validation using Fluent Validation

  1. Pingback: Fluent Validation with Web Api 2 | no dogma blog

  2. Pingback: Fluent Validation in ASP.NET Core | no dogma blog

Leave a Reply

Your email address will not be published. Required fields are marked *