You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.3 KiB
40 lines
1.3 KiB
2 years ago
|
using FluentValidation;
|
||
|
using FluentValidation.Results;
|
||
|
|
||
1 year ago
|
namespace Recyclarr.Common.FluentValidation;
|
||
2 years ago
|
|
||
|
public static class FluentValidationExtensions
|
||
|
{
|
||
|
// From: https://github.com/FluentValidation/FluentValidation/issues/1648
|
||
2 years ago
|
// ReSharper disable once UnusedMethodReturnValue.Global
|
||
2 years ago
|
public static IRuleBuilderOptions<T, TProperty?> SetNonNullableValidator<T, TProperty>(
|
||
|
this IRuleBuilder<T, TProperty?> ruleBuilder, IValidator<TProperty> validator, params string[] ruleSets)
|
||
|
{
|
||
|
var adapter = new NullableChildValidatorAdaptor<T, TProperty>(validator, validator.GetType())
|
||
|
{
|
||
|
RuleSets = ruleSets
|
||
|
};
|
||
|
|
||
|
return ruleBuilder.SetAsyncValidator(adapter);
|
||
|
}
|
||
|
|
||
|
public static IEnumerable<TSource> IsValid<TSource, TValidator>(
|
||
|
this IEnumerable<TSource> source, TValidator validator,
|
||
|
Action<List<ValidationFailure>, TSource>? handleInvalid = null)
|
||
1 year ago
|
where TValidator : IValidator<TSource>
|
||
2 years ago
|
{
|
||
|
foreach (var s in source)
|
||
|
{
|
||
|
var result = validator.Validate(s);
|
||
1 year ago
|
if (result is {IsValid: true})
|
||
2 years ago
|
{
|
||
|
yield return s;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
handleInvalid?.Invoke(result.Errors, s);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|