1

My validator checks if the property Name is unique, in the sense that no other item of the collection ContentSections has the same value.

public class ContentSectionDtoValidator : AbstractValidator<ContentSectionDto>
{
    public ContentSectionDtoValidator(EditContentSectionsDto editContentSectionsDto)
    {
        RuleFor(x => x.Name)
            .Must(x => editContentSectionsDto.ContentSections.Count(contentSection => contentSection.Name == x) == 1)
            .WithMessage("The Name '{0}' has already been used. Names must ne unique.", x => x.Name);
    }
}

In order to achieve that, I passed as parameter to the constructor the parent model, which contains the entire collection, so I can compare the Name of the current item to the one of all the other items of the collection.

This works, but obviously in case the Name if found to be in use by any other item, a validation error for each match is printed.

enter image description here

Is there a way to only print ONE message even if the condition is matched many times?

1
  • 1
    You can use RuleForEach method in the parent model validator. Look at example here. Commented Apr 6, 2017 at 19:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.