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();
}
}
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With