Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw exception on single FluentValidation rule failure

Using FluentValidation, is it possible to throw an exception on a single rule failure? For example, I would like to call Validate() and for the first rule below to simply validate but the second to throw an exception if false.

RuleFor(x => x.Title)
    .NotEmpty()
    .WithMessage("Please add a title for the project");

RuleFor(x => x.UserId)
    .NotEmpty()
    .WithMessage("User not supplied");

I'm probably trying to force FluentValidation to do something it is not designed to do. And I am aware of the ValidateAndThrow() method, but this will throw an exception on any failure.

like image 254
Digbyswift Avatar asked Dec 12 '22 12:12

Digbyswift


1 Answers

Normally it's better to validate all properties and then report the result, though there can be a case where it makes no sense to continue validating (in my case it was when a "tenant" identifier was missing in a request).

Just change the second rule to something like this (tested with Automapper 5.2, C# 6):

RuleFor(x => x.Title)
    .NotEmpty()
    .WithMessage("Please add a title for the project");

RuleFor(x => x.UserId)
    .NotEmpty()
    .OnAnyFailure(x =>
    {
        throw new ArgumentException(nameof(x.UserId));
    });
  • If you call IValidator.Validate(...) and the first rule fails then it will simply be listed in the Errors list of the result.
  • If the second rule fails, the call to Validate will raise the ArgumentException and obviously no result is returned.
  • If you would call the ValidateAndThrow extension method then it would either simply return, throw an ArgumentException if the second rule fails or throw a ValidationException if one of the other rules failed.
like image 187
JBert Avatar answered Dec 26 '22 00:12

JBert