简体   繁体   中英

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.

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.

Yes. Try something along these lines -

Add FluentValidation and FluentValidation.TestHelper to your directives.

    private readonly IValidator<ItemViewModel> validator = new ItemValidator(); 
    //Assumes your fluent validation is in ItemValidator and your view model is ItemViewModel

    [Test]
    public void Headline_ShouldNotBeEmpty()
    {
        validator.ShouldHaveValidationErrorFor(f => f.message, string.Empty);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM