#region ========================================================================= USING ===================================================================================== using FluentValidation; using Microsoft.Extensions.Options; using System; using System.Linq; #endregion namespace Lumina.Infrastructure.Common.Validation; /// /// Provides options for fluent validation of a specific options type. /// /// The type of options being validated. public class FluentValidationOptions : IValidateOptions where TOptions : class { private readonly IValidator _validator; /// /// Gets the name of the options being validated. /// public string? Name { get; } /// /// Initializes a new instance of the class. /// /// The name of the options being validated. This can be . /// The validator instance used to validate the options. public FluentValidationOptions(string? name, IValidator validator) { Name = name; _validator = validator; } /// /// Validates the specified . /// /// The name of the options instance being validated. /// The options instance to validate. /// A that indicates whether the validation was successful or not. public ValidateOptionsResult Validate(string? name, TOptions options) { // check if the name of the options is specified and matches the provided one if (Name is not null && Name != name) return ValidateOptionsResult.Skip; ArgumentNullException.ThrowIfNull(options, nameof(options)); // don't go further if the options are null FluentValidation.Results.ValidationResult validationResult = _validator.Validate(options); // validate the options using the validator // return a response based on the validation result if (validationResult.IsValid) return ValidateOptionsResult.Success; // if the validation fails, collect the error messages string[] errors = validationResult.Errors.Select(x => $"Options validation failed for '{x.PropertyName}' with error: '{x.ErrorMessage}'") .ToArray(); // and return them with a failure result return ValidateOptionsResult.Fail(errors); } }