question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validate uniqness in child collection

See original GitHub issue

Hi, All. I have a class with some property of type collection strings. For example,

public class TestClass
{
    public List<InnerCollection> Collection { get; set; }
}

public class InnerCollection
{
    public string Name { get; set; }
}

RuleForEach(x => x.Collection)
        .Must((parent, col) => parent.Collection.GroupBy(x => x.Name).Count() > 1 })
        .WithMessage("The {0} symbol already exists.",
        (parent, col) => col.Name);

Can I create validation rule that returned for me only ONE validation message?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
JeremySkinnercommented, Nov 6, 2015

You’d need to write a custom validator to manually handle the logic for that, which then concatenates the failed items together into a single message. Something like this should work:

public class UniqueInnerCollectionValidator : PropertyValidator {
    public UniqueInnerCollectionValidator() 
        : base("The following symbols already exist: {symbols}") {

    }

    protected override bool IsValid(PropertyValidatorContext context) {
        var listOfCollection = context.PropertyValue as List<InnerCollection>;
        if (listOfCollection == null) {
            return true;
        }

        var nonUniqueKeys = listOfCollection.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(x => x.Key).ToList();

        if (nonUniqueKeys.Count > 0) {
            string failedItems = string.Join(", ", nonUniqueKeys.ToArray());
            context.MessageFormatter.AppendArgument("symbols", failedItems);
            return false;
        }

        return true;
    }
}

…useable like this:

RuleFor(x => x.Collection).SetValidator(new UniqueInnerCollectionValidator());

The error message contains all the names that caused failures concatenated together.

0reactions
JeremySkinnercommented, Nov 11, 2015

No, sorry - AddRule basically completely bypasses the standard fluent interface and allows you to write your own rules, so you’d have to also include any other validation (null checks etc) inside the delegate.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Rails how to validate uniqueness across child objects with ...
In a nested form, I want the user to have the ability to create or modify all of a Parent 's Childs at...
Read more >
'validates_uniqueness_of' ignored if ' ...
validates_associated works fine with validates_uniqueness of if you are adding a single record to a collection. Where it breaks is when you use ......
Read more >
How to Rippling validation effects from child to parent? - Rails
I'm new to rails and am experiencing problems with validations. I have the following models: class Client < ActiveRecord::Base
Read more >
How to validate value in child object against ...
I have a similar scenario. I have a collection of child objects and I need to compare values between them. Since the children...
Read more >
A Deep Dive into Active Record Validations
Validating inclusion, which checks whether a given input includes values from a provided set and works very well with enumerables.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found