| | | 1 | | // ReSharper disable once CheckNamespace |
| | | 2 | | namespace FluentValidation; |
| | | 3 | | |
| | | 4 | | /// <summary>Rules for enum properties.</summary> |
| | | 5 | | public static class FluentValidationEnumHelpers |
| | | 6 | | { |
| | | 7 | | /// <summary>The value must be set and be a defined member of its enum.</summary> |
| | | 8 | | /// <typeparam name="T">The validated type.</typeparam> |
| | | 9 | | /// <typeparam name="TProperty">The enum (or nullable enum) type.</typeparam> |
| | | 10 | | /// <param name="ruleBuilder">The rule builder.</param> |
| | | 11 | | /// <returns>The rule builder options.</returns> |
| | | 12 | | public static IRuleBuilderOptions<T, TProperty> NotEmptyEnum< T, TProperty >( this IRuleBuilder<T, TProperty> ruleBu |
| | 3 | 13 | | => ruleBuilder.Must( ( _, value, context ) => value is not null && new EnumValidator<T, TProperty>().IsValid( co |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// The value must be a defined member of its enum (or empty); when <paramref name="nullable"/> returns <see langwor |
| | | 17 | | /// it must also be set (a <see langword="null"/> <paramref name="nullable"/> allows empty). |
| | | 18 | | /// </summary> |
| | | 19 | | /// <typeparam name="T">The validated type.</typeparam> |
| | | 20 | | /// <typeparam name="TProperty">The enum (or nullable enum) type.</typeparam> |
| | | 21 | | /// <param name="ruleBuilder">The rule builder.</param> |
| | | 22 | | /// <param name="nullable">Decides, per instance and value, whether an empty value is allowed.</param> |
| | | 23 | | /// <returns>The rule builder options.</returns> |
| | | 24 | | public static IRuleBuilderOptions<T, TProperty> NotEmptyEnumIf< T, TProperty >( this IRuleBuilder<T, TProperty> rule |
| | 3 | 25 | | => ruleBuilder.Must( ( entity, value, context ) => |
| | 3 | 26 | | { |
| | 3 | 27 | | var allowsEmpty = nullable?.Invoke( entity, value ) ?? true; |
| | 3 | 28 | | |
| | 3 | 29 | | |
| | 3 | 30 | | return ( allowsEmpty || value is not null ) && new EnumValidator<T, TProperty>().IsVali |
| | 3 | 31 | | } ).WithErrorCode( nameof( NotEmptyEnumIf ) ); |
| | | 32 | | } |