title: FluentValidation LogOnFailure override
body: <p>Inside my validator class I have couple of rules.<br/>
  I need to log to database some validation errors.</p>
  
  <p>Here are my validators:</p>
  
  <pre><code>RuleFor(u =&gt; u.LastName)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotEmpty().WithMessage("Last name is required")
      .Length(3, 20).WithMessage("Must have between 3 and 20 letters");
  
  RuleFor(u =&gt; u.BirthDate)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotNull().WithMessage("Birth date is required")
      .Must(c =&gt; c &gt; new DateTime(1920, 01, 01)).WithMessage("Too old");
  
  RuleFor(u =&gt; u.Age)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotNull().WithMessage("This is required")
      .GreaterThan(18).WithMessage("Must be at least 18")
      .Must((model, age, context) =&gt;
      {
          DateTime today = DateTime.Today;
          int ageToCompare = today.Year - model.BirthDate.Year;
          return ageToCompare == age;
      }).WithMessage("Invalid age");
  </code></pre>
  
  <p>For above rules I'd like to log only specific error messages.
  I'm aware that I can use OnAnyFailure like this:</p>
  
  <pre><code>RuleFor(u =&gt; u.Age)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotNull().WithMessage("This is required")
      .GreaterThan(18).WithMessage("Must be at least 18").OnAnyFailure(LogOnFailure)
      .Must((model, age, context) =&gt;
      {
          DateTime today = DateTime.Today;
          int ageToCompare = today.Year - model.BirthDate.Year;
          return ageToCompare == age;
      }).WithMessage("Invalid age").OnAnyFailure(LogOnFailure)
  
  private void LogOnFailure(CreateAccountBindingModel obj))
      {
          Debug.WriteLine(obj);
      }
  </code></pre>
  
  <p>but this way I won't be able to log anything useful, because <code>OnAnyFailure</code> takes BindingModel as parameter, so I'll only get values user entered without error messages.</p>
  
  <p>I've tried to create extension method that would work as <code>OnAnyFailure</code> but because I'm new to FluentValidation I wasn't able to even compile my code.</p>
  
  <p>Below is my code:</p>
  
  <pre><code>public static class IRuleBuilderOptionsExtensions
  {
      public static IRuleBuilderOptions&lt;T, TProperty&gt; OnAnyFailure&lt;T, TProperty&gt;(this IRuleBuilderOptions&lt;T, TProperty&gt; rule, Action&lt;T, PropertyValidatorContext&gt; onFailure)
      {
          return rule;
          //return rule.Configure(config =&gt; {
          //  config.OnFailure = onFailure.CoerceToNonGeneric();
          //});
      }
  }
  </code></pre>
  
  <p>This way I could be able to call:</p>
  
  <pre><code>private void LogOnFailure(CreateAccountBindingModel obj), PropertyValidatorContext context)
  {
      //log logic
  }
  </code></pre>
  
  <p>Basically what I need is to create override for <code>LogOnFailure</code> that will be able to access PropertyValidatorContext.</p>