In a project I have a set of validator objects, of which the Validate
yield returns a ValidationResult
for each error. In turn, these are collected and an exception is thrown. I've stolen this from here: Validation: How to inject A Model State wrapper with Ninject?
When an object which needs to be validated has complex properties which also need to be validated, I end up with clunky code like this (my problem is the foreach
loop):
public class MembershipValidator
{
public override IEnumerable<ValidationResult> Validate(Membership entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
foreach (var result in userValidator.Validate(entity.User))
{
yield return result;
}
}
}
Where the UserValidator
in this case also has several yield return
statements (of which one is shown here):
public class UserValidator
{
public override IEnumerable<ValidationResult> Validate(User entity)
{
if (entity == null)
{
throw new ArgumentNullException();
}
if (entity.BirthDate == DateTime.MinValue)
{
yield return new ValidationResult("User", "BirthDate is mandatory");
}
}
}
Is there any way to write the code in the "parent" validator more concise? It's now riddled with foreach
loops.
Plainly writing the following code builds, but doesn't execute:
userValidator.Validate(entity.User);
And the following doesn't compile:
return userValidator.Validate(beschouwing.User);