Nerf
Nerf

Reputation: 938

FluentValidation and collection of object its property should be unique

I have class:

Sponsored { int Order };

And I have collection of it:

IEnumerable<Sponsored> sponsored; 

I want to check if Order is unique for this collection.

Can I do it via FluentValidation?

I have:

SponsoredValidator : AbstractValidator<IEnumerable<Sponsored>>

and

SponsoredValidator : AbstractValidator<Sponsored>

@Edit: It should be connected with WebAPI POST method via ValidationAttribute

[Validator(typeof(SponsoredValidator))]

Upvotes: 5

Views: 9017

Answers (1)

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18023

public class SponsoredCollectionValidator : AbstractValidator<IEnumerable<Sponsored>>
{
    private class SponsoredComparer : IEqualityComparer<Sponsored>
    {
        public bool Equals(Sponsored x, Sponsored y) => x?.Order == y?.Order;
        public int GetHashCode(Sponsored obj) => obj.Order;
    }

    public SponsoredCollectionValidator()
    {
       RuleFor(coll => coll)
           .Must(coll => coll.Distinct(new SponsoredComparer()).Count() == coll.Count())
           .WithMessage("Elements are not unique.");
    }
}

Upvotes: 10

Related Questions