Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation, is possible an inline validation?

I have a the following operation:

public void Save (Customer c, IEnumerable <Product> products)
{
    // Validate that you have entered at least one product.
    if (!produtos.Any())
        throw new ArgumentOutOfRangeException("products");
}

Inline, without using inheritance (eg AbstractValidator ), as would this same operation using the FluentValidation library?

like image 454
Vinicius Gonçalves Avatar asked Jun 02 '26 07:06

Vinicius Gonçalves


1 Answers

This is not supported yet:

public void DoOperation(List<string> strings)
{ 
    var validator = new InlineValidator<List<string>>();
    validator.RuleFor(l => l).Must(l => l.Any()).WithMessage("No one");
    validator.ValidateAndThrow(strings)     
}

On this case, we have to throw ValidationException manually.

like:

public void DoOperation(List<string> strings)
{ 
    if (!strings.Any())
    {
        var failures = new List<ValidationFailure>();
        failures.Add(new ValidationFailure("strings", "Must have at less one."));

        throw new ValidationException(failures);
    }
}

See:

https://fluentvalidation.codeplex.com/discussions/579227

like image 71
Vinicius Gonçalves Avatar answered Jun 05 '26 00:06

Vinicius Gonçalves