Skip to content

Instantly share code, notes, and snippets.

@JeremySkinner
Created August 29, 2013 16:05
Show Gist options
  • Save JeremySkinner/6380054 to your computer and use it in GitHub Desktop.
Save JeremySkinner/6380054 to your computer and use it in GitHub Desktop.
public static class MyExtensions {
public IRuleBuilderOptions<T, TProperty> SetValidator<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, Func<T, IValidator<TProperty>> validatorThunk) {
return ruleBuilder.SetValidator(new LazyValidatorAdaptor<T, TProperty>(validatorThunk));
}
private class LazyValidatorAdaptor<T, TProperty> : NoopPropertyValidator {
Func<T, IValidator<TProperty>> _validatorThunk;
public LazyValidatorAdaptor(Func<T, IValidator<TProperty>> validatorThunk) {
_validatorThunk = validatorThunk;
}
public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
var validator = _validatorThunk((T)context.Instance);
var adaptor = new ChildValidatorAdaptor(validator);
return adaptor.Validate(context);
}
}
}
// Useable like this:
// RuleFor(x => x.Foo).SetValidator(x => new FooValidator(x));
@petemounce
Copy link

So, this would apply the child validator, then allow me to chain on subsequent rules, and assumes I'd set CascadeMode to StopOnFirstFailure...?

Something like (coding from memory; currently offsite):

RuleFor(x => x.Tenant).SetValidator(new TenantValidator()); // make sure tenant is cool
RuleFor(x => x.Foo)
  .SetValidator(x => new FooValidator(x)); // only fires if Tenant is valid...?

Not sure I've followed, sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment