Search code examples
c#validationfluentvalidation

How to call a method after fluent validation faliure


I want to run a method if a fluent validation method fails.

RuleFor(x => x.SheepName)
            .Must(x => x.SheepName == null)
            .When(x => x.HasSheep == false)
            .Otherwise(callMethod());

So in this case, if the HasSheep value is false but the SheepName is still given, then I want to run a method (in the example the method is called 'callMethod()').

I have made up the .Otherwise statement, so looking for what this whole line '.Otherwise(callMethod());' needs to be..


Solution

  • Current version:

    OnFailure (and OnAnyFailure) were removed in V11. From the release notes:

    If you were previously using OnFailure or OnAnyFailure to perform custom logic after validation, we recommend using a Custom validator instead.

    Older versions:

    You can use OnFailure(…), as documented here

    You can make use of the OnAnyFailure and OnFailure (as of 8.0) callbacks to run a method if validation fails.

    RuleFor(x => x.SheepName)
           .Must(x => x.SheepName == null)
           .When(x => x.HasSheep == false)
           .OnFailure(x => callMethod());