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));
});
IValidator.Validate(...)
and the first rule fails then it will simply be listed in the Errors
list of the result.Validate
will raise the ArgumentException
and obviously no result is returned.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With