Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a List of Guid using FluentValidation

I am trying to validate a List of Guid using Fluent Validation.
My Ids list should have at least one Guid Id. I did some research and found similar questions answered, and the closest I came to a solution was implementing it like below, but it still doesn't work. When I make a request even if I send the List of Ids with values, it gives me the error message that the Value cannot be null. What am I doing wrong?

    public class Data
    {
        public List<Guid> Ids{ get; set; }
    }

    public class DataValidator : AbstractValidator<Data>
    {
        public DataValidator()
        {
            RuleFor(d => d.Ids).SetCollectionValidator(new GuidValidator());
        }
    }

    public class GuidValidator : AbstractValidator<Guid>
    {
        public GuidValidator()
        {
            RuleFor(x => x).NotNull().NotEmpty();
        }
    }

I have tried this validator as well but it didn't work:

    public class DataValidator : AbstractValidator<Data>
    {
        public DataValidator()
        {
            RuleForEach(d => d.Ids).NotNull().NotEmpty();
        }
    }
like image 564
A.Blanc Avatar asked Apr 26 '18 11:04

A.Blanc


People also ask

What is FluentValidation C#?

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.

Should I use fluent validation?

Summary. FluentValidation provides a great alternative to Data Annotations in order to validate models. It gives better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.


1 Answers

You can just chain validators:

public class DataValidator : AbstractValidator<Data>
    {
        public DataValidator()
        {
            RuleFor(d => d.Ids)
                .NotNull() //validates whether Ids collection is null
                .NotEmpty() //validates whether Ids collection is empty
                .SetCollectionValidator(new GuidValidator()); //validates each element inside Ids collection using GuidValidator
        }
    }

Also, since Guid is a struct, you don't have to use NotNull() validation inside GuidValidator:

public class GuidValidator : AbstractValidator<Guid>
    {
        public GuidValidator()
        {
            RuleFor(x => x).NotEmpty();
        }
    }
like image 128
Darjan Bogdan Avatar answered Sep 18 '22 11:09

Darjan Bogdan