Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Collection Validation & Parent Context

$
0
0

I have read through many of the discussions posted here and am sure this isn't possible but couldn't find a direct answer:

Is it possible to somehow get the parent context available to a child collection validator?  

It makes sense that this was designed so that the validators go against properties available on the subject being validated - but I think collections are a little different.

Given this example where a "WorkDay" has a collection of work items that need assigning and a collection of work assignments that have been assigned. 

 

publicclass WorkDay
{public DateTime Date { get; set; }public IEnumerable<WorkItem> WorkItems { get; set; } public IEnumerable<Assignment> Assignments { get; set; } 
}publicclass Assignment
{public Person Person { get; set; }public WorkItem WorkItem { get; set; }
}

 

It would be great to create a "WorkItem" validator that confirmed each "WorkItem" was assigned.  One way would be to have a two-way relationship so that a "WorkItem" had reference to its parent "WorkDay" so it could have access to the assignments to check if it was assigned.  However, it is not always feasible / possible to alter the domain to include these relationships.

It would be fantastic if we could do something like:

publicclass WorkDayValidator : AbstractValidator<WorkDay>
{public WorkDayValidator()
    {
        RuleFor(workDay => workDay.Date).NotNull();
        RuleFor(workDay => workDay.WorkItems).SetCollectionValidator(workDay => new WorkItemValidator(workDay));
    }
}publicclass WorkItemValidator : AbstractValidator<WorkItem>
{public WorkItemValidator(WorkDay workDay)
    {var assignedWorkItems = from assignment in workDay.Assignmentsselect assignment.WorkItem;

        RuleFor(workItem => workItem.Description).NotEmpty();
        RuleFor(workItem => workItem)
            .Must(workItem => assignedWorkItems.Contains(workItem))
            .WithMessage("{0} has not been assigned", workItem => workItem.Description);
    }
}

Is there currently a way to accomplish the same result?

Thanks!

 


Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>