Merge pull request #156 from BinaryAlley/refactor/replace-fluentvalidation-with-custom-validation

Replaces FluentValidation with the custom validation framework in the web project
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-08-19 10:55:59 -07:00
commit ea6b1329cf
19 files changed
+1020 -104

No files matched your search

@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Enums.Authorization;
@@ -10,10 +9,12 @@ using Lumina.Presentation.Web.Common.Http;
using Lumina.Presentation.Web.Common.Localization;
using Lumina.Presentation.Web.Common.Security;
using Lumina.Presentation.Web.Common.Services;
using Lumina.Presentation.Web.Common.Validation;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Localization.Routing;
@@ -51,14 +52,14 @@ public static class PresentationWebLayerServices
public static IServiceCollection AddPresentationWebLayerServices(this IServiceCollection services)
{
services.AddControllersWithViews()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.MaxDepth = 256;
jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
.AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.MaxDepth = 256;
jsonOptions.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// configure the locations where the Razor view engine looks for views and layouts, since the views live under the Core directory
services.Configure<RazorViewEngineOptions>(razorViewEngineOptions =>
@@ -97,10 +98,7 @@ public static class PresentationWebLayerServices
documentOptions.ShortSchemaNames = true;
});
// configure URL-based localization
services.AddLocalization(localizationOptions =>
{
localizationOptions.ResourcesPath = "Core/Resources";
});
services.AddLocalization(localizationOptions => localizationOptions.ResourcesPath = "Core/Resources");
// resolve the resources of the views that live under the Core/Views directory
services.AddSingleton<IHtmlLocalizerFactory, CoreHtmlLocalizerFactory>();
@@ -257,8 +255,21 @@ public static class PresentationWebLayerServices
sessionOptions.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance
});
// scan the current assembly for validators and register them to the DI container
services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);
// scan the current assembly for validators and register them as singletons in the DI container
foreach (Type validatorType in typeof(Program).Assembly.GetTypes())
{
if (validatorType.IsInterface || validatorType.IsAbstract || validatorType.IsGenericTypeDefinition)
continue;
foreach (Type contract in validatorType.GetInterfaces())
{
if (contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(Validation.IValidator<>))
{
services.AddSingleton(contract, validatorType);
break;
}
}
}
// handle transient errors like network timeouts or intermittent failures
AsyncRetryPolicy<HttpResponseMessage> retryPolicy = Policy<HttpResponseMessage>
@@ -287,6 +298,7 @@ public static class PresentationWebLayerServices
// enable access to the current HTTP context in non-controller classes
services.AddHttpContextAccessor();
services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 10 * 1024 * 1024);
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
services.AddScoped<IAuthorizationHandler, RoleAuthorizationHandler>();
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Validation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
@@ -10,22 +9,22 @@ namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Extension methods for adding configuration related options services to the DI container via <see cref="OptionsBuilder{TOptions}"/>.
/// </summary>
public static class OptionsBuilderFluentValidationUtilities
public static class OptionsBuilderValidationUtilities
{
/// <summary>
/// Extension method to add fluent validation to the options validation pipeline.
/// Extension method to add validation to the options validation pipeline.
/// </summary>
/// <typeparam name="TOptions">The type of options being validated.</typeparam>
/// <param name="optionsBuilder">The options builder to add the validation to.</param>
/// <remarks>
/// This method allows validating options of type <typeparamref name="TOptions"/> using a FluentValidation validator registered in the DI container.
/// This method allows validating options of type <typeparamref name="TOptions"/> using a validator registered in the DI container.
/// </remarks>
/// <returns>The same <see cref="OptionsBuilder{TOptions}"/> instance, to allow for chaining.</returns>
public static OptionsBuilder<TOptions> ValidateFluently<TOptions>(this OptionsBuilder<TOptions> optionsBuilder) where TOptions : class
{
// register a singleton instance of IValidateOptions<TOptions> using FluentValidation
// register a singleton instance of IValidateOptions<TOptions> using the validator
optionsBuilder.Services.AddSingleton<IValidateOptions<TOptions>>(
serviceProvider => new FluentValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
serviceProvider => new ValidationOptions<TOptions>(optionsBuilder.Name, serviceProvider.GetRequiredService<IValidator<TOptions>>()));
return optionsBuilder;
}
}
}
@@ -0,0 +1,392 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Validation;
using System;
using System.Collections;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Presentation.Web.Common.Utilities;
/// <summary>
/// Validator extension methods for the <see cref="IRuleBuilder{TRequest, TProperty}"/> to define common validation rules.
/// </summary>
public static class ValidatorUtilities
{
/// <summary>
/// Defines a validation rule that ensures the integer property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int> GreaterThan<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable integer property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the long property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, long> GreaterThan<TRequest>(this IRuleBuilder<TRequest, long> ruleBuilder, long valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable long property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, long?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, long?> ruleBuilder, long valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the decimal property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable decimal property is greater than the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal?> GreaterThan<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the time span property is greater than the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TimeSpan> GreaterThan<TRequest>(this IRuleBuilder<TRequest, TimeSpan> ruleBuilder, TimeSpan valueToCompare)
{
return ruleBuilder.Must(value => value > valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the integer property is greater than or equal to the specified value.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable integer property is greater than or equal to the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the nullable decimal property is greater than or equal to the specified value.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="valueToCompare">The value that the property must be greater than or equal to.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, decimal?> GreaterThanOrEqualTo<TRequest>(this IRuleBuilder<TRequest, decimal?> ruleBuilder, decimal valueToCompare)
{
return ruleBuilder.Must(value => !value.HasValue || value.Value >= valueToCompare);
}
/// <summary>
/// Defines a validation rule that ensures the property is not <see langword="null"/>.
/// </summary>
/// <remarks>
/// This rule checks reference/nullable-value nullness only. Combine with
/// <see cref="NotEmpty{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to also reject empty values.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> NotNull<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
{
return ruleBuilder.Must(value => value is not null);
}
/// <summary>
/// Defines a validation rule that ensures the property is not empty.
/// </summary>
/// <remarks>
/// This rule is type-aware: a <see cref="string"/> is checked for white-space only content, a <see cref="Guid"/>
/// is checked against <see cref="Guid.Empty"/>, and any <see cref="IEnumerable"/> is checked for having at least
/// one item. If the property is <see langword="null"/>, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> NotEmpty<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
{
return ruleBuilder.Must(value => value switch
{
null => false,
string stringValue => stringValue.Trim().Length > 0,
Guid guidValue => guidValue != Guid.Empty,
IEnumerable enumerable => enumerable.GetEnumerator().MoveNext(),
_ => true
});
}
/// <summary>
/// Defines a validation rule that ensures the value is a defined member of the specified enumeration type.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TEnum> IsInEnum<TRequest, TEnum>(this IRuleBuilder<TRequest, TEnum> ruleBuilder) where TEnum : struct, Enum
{
return ruleBuilder.Must(value => Enum.IsDefined(value));
}
/// <summary>
/// Defines a validation rule that ensures a nullable enum value is either <see langword="null"/> or a defined member of the specified enumeration type.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TEnum">The type of the enumeration.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TEnum?> IsInEnum<TRequest, TEnum>(this IRuleBuilder<TRequest, TEnum?> ruleBuilder) where TEnum : struct, Enum
{
return ruleBuilder.Must(value => value.HasValue && Enum.IsDefined(value.Value));
}
/// <summary>
/// Defines a validation rule that ensures the string property does not exceed the specified maximum length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule passes.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="maximumLength">The maximum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> MaximumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int maximumLength)
{
return ruleBuilder.Must(value => value is not string stringValue || stringValue.Length <= maximumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property is at least the specified minimum length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumLength">The minimum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> MinimumLength<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property has exactly the specified length.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="length">The exact allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int length)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length == length);
}
/// <summary>
/// Defines a validation rule that ensures the string property length is within the specified inclusive range.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumLength">The minimum allowed length of the property.</param>
/// <param name="maximumLength">The maximum allowed length of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Length<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, int minimumLength, int maximumLength)
{
return ruleBuilder.Must(value => value is string stringValue && stringValue.Length >= minimumLength && stringValue.Length <= maximumLength);
}
/// <summary>
/// Defines a validation rule that ensures the string property matches the specified regular expression pattern.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails (use
/// <see cref="When{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty}, Func{TRequest, bool})"/> to skip optional properties).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="regexPattern">The regular expression pattern the property must match.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, string regexPattern)
{
return ruleBuilder.Must(value => value is string stringValue && Regex.IsMatch(stringValue, regexPattern));
}
/// <summary>
/// Defines a validation rule that ensures the string property matches the regular expression pattern selected from the request instance.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/> or not a string, this rule fails.
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="regexPatternSelector">A function that selects the regular expression pattern to match against from the request instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Matches<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, string> regexPatternSelector)
{
return ruleBuilder.Must((instance, value) => value is string stringValue && Regex.IsMatch(stringValue, regexPatternSelector(instance)));
}
/// <summary>
/// Defines a validation rule that ensures the integer property is within the specified inclusive range.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int> ruleBuilder, int minimumValue, int maximumValue)
{
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
}
/// <summary>
/// Defines a validation rule that ensures the nullable integer property is within the specified inclusive range.
/// </summary>
/// <remarks>
/// If the property is <see langword="null"/>, this rule passes (use <see cref="NotNull{TRequest, TProperty}(IRuleBuilder{TRequest, TProperty})"/> to check for missing values).
/// </remarks>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, int?> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, int?> ruleBuilder, int minimumValue, int maximumValue)
{
return ruleBuilder.Must(value => !value.HasValue || (value.Value >= minimumValue && value.Value <= maximumValue));
}
/// <summary>
/// Defines a validation rule that ensures the unsigned short property is within the specified inclusive range.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, ushort> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, ushort> ruleBuilder, ushort minimumValue, ushort maximumValue)
{
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
}
/// <summary>
/// Defines a validation rule that ensures the character property is within the specified inclusive range.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, char> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, char> ruleBuilder, char minimumValue, char maximumValue)
{
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
}
/// <summary>
/// Defines a validation rule that ensures the long property is within the specified inclusive range.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="minimumValue">The minimum allowed value of the property.</param>
/// <param name="maximumValue">The maximum allowed value of the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, long> InclusiveBetween<TRequest>(this IRuleBuilder<TRequest, long> ruleBuilder, long minimumValue, long maximumValue)
{
return ruleBuilder.Must(value => value >= minimumValue && value <= maximumValue);
}
/// <summary>
/// Defines a validation rule that ensures the property is equal to another property of the request.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="ruleBuilder">The rule builder instance.</param>
/// <param name="comparisonSelector">A function that selects the property the validated property must equal.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public static IRuleBuilder<TRequest, TProperty> Equal<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder, Func<TRequest, TProperty> comparisonSelector)
{
return ruleBuilder.Must((instance, value) => Equals(value, comparisonSelector(instance)));
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Base class for creating validators for a specific type.
/// </summary>
/// <typeparam name="TRequest">The type of the instance to be validated.</typeparam>
public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
{
private readonly List<IValidationRule<TRequest>> _rules = [];
/// <summary>
/// Defines a validation rule for a specific property on the request being validated.
/// </summary>
/// <typeparam name="TProperty">The type of the property being validated.</typeparam>
/// <param name="propertySelector">A function that selects the property to validate from the request instance.</param>
/// <returns>An <see cref="IRuleBuilder{TRequest, TProperty}"/> instance to configure the rule fluently.</returns>
public IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
{
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
_rules.Add(rule);
return rule;
}
/// <summary>
/// Defines a validation rule that is evaluated against each item within a collection property on the request being validated.
/// </summary>
/// <typeparam name="TItem">The type of the items in the collection being validated.</typeparam>
/// <param name="collectionSelector">A function that selects the collection to validate from the request instance.</param>
/// <returns>An <see cref="IRuleBuilder{TRequest, TItem}"/> instance to configure the per-item rule fluently.</returns>
public IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
{
ValidationRuleForEach<TRequest, TItem> rule = new(collectionSelector);
_rules.Add(rule);
return rule;
}
/// <summary>
/// Validates the specified request instance against all defined rules.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>A list of validation errors. If the instance is valid, the list will be empty.</returns>
public List<Error> Validate(TRequest instance)
{
List<Error> errors = [];
foreach (IValidationRule<TRequest> rule in _rules)
errors.AddRange(rule.Validate(instance));
return errors;
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Provides a fluent API for building validation rules for a specific type.
/// </summary>
/// <typeparam name="TRequest">The type of the instance being validated.</typeparam>
/// <typeparam name="TProperty">The type of the specific property on the instance that the rule applies to.</typeparam>
public interface IRuleBuilder<TRequest, TProperty>
{
/// <summary>
/// Specifies a condition that the property must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate);
/// <summary>
/// Specifies a condition that both the request instance and the property value must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> predicate);
/// <summary>
/// Specifies a condition that must be met for the validation rule to be executed.
/// </summary>
/// <param name="condition">A function evaluating the request instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition);
/// <summary>
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
/// </summary>
/// <param name="error">The specific error to return upon failure.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> WithError(Error error);
/// <summary>
/// Defines nested validation rules for the complex property being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> configure);
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Interface for triggering validator evaluation.
/// </summary>
/// <typeparam name="TRequest">The type of the instance being evaluated.</typeparam>
internal interface IValidationRule<in TRequest>
{
/// <summary>
/// Evaluates the validation rule against the specified request instance.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>The <see cref="Error"/>s produced by this rule; empty if the rule passes.</returns>
IEnumerable<Error> Validate(TRequest instance);
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Interface for validating instances of a specific type.
/// </summary>
/// <typeparam name="TRequest">The type of the instance to be validated.</typeparam>
public interface IValidator<in TRequest>
{
/// <summary>
/// Validates the specified request instance against the defined rules.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>A list of validation errors. If the instance is valid, the list will be empty.</returns>
List<Error> Validate(TRequest instance);
}
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Concrete <see cref="AbstractValidator{TRequest}"/> used to declare validation rules inline for nested complex properties.
/// </summary>
/// <typeparam name="TRequest">The type of the instance to be validated.</typeparam>
public class InlineValidator<TRequest> : AbstractValidator<TRequest>
{
}
@@ -1,17 +1,18 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Primitives;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Provides options for fluent validation of a specific options type.
/// Provides options validation for a specific options type using the validation framework.
/// </summary>
/// <typeparam name="TOptions">The type of options being validated.</typeparam>
public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> where TOptions : class
public class ValidationOptions<TOptions> : IValidateOptions<TOptions> where TOptions : class
{
private readonly IValidator<TOptions> _validator;
@@ -21,11 +22,11 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
public string? Name { get; }
/// <summary>
/// Initializes a new instance of the <see cref="FluentValidationOptions{TOptions}"/> class.
/// Initializes a new instance of the <see cref="ValidationOptions{TOptions}"/> class.
/// </summary>
/// <param name="name">The name of the options being validated. This can be <see langword="null"/>.</param>
/// <param name="validator">The validator instance used to validate the options.</param>
public FluentValidationOptions(string? name, IValidator<TOptions> validator)
public ValidationOptions(string? name, IValidator<TOptions> validator)
{
Name = name;
_validator = validator;
@@ -45,15 +46,14 @@ public class FluentValidationOptions<TOptions> : IValidateOptions<TOptions> wher
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
List<Error> validationResult = _validator.Validate(options); // validate the options using the validator
// return a response based on the validation result
if (validationResult.IsValid)
if (validationResult.Count == 0)
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();
string[] errors = [.. validationResult.Select(error => $"Options validation failed for '{error.Code}' with error: '{error.Description}'")];
// and return them with a failure result
return ValidateOptionsResult.Fail(errors);
@@ -0,0 +1,156 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Defines a validation rule that evaluates a specific property of an instance.
/// </summary>
/// <typeparam name="TRequest">The type of the instance being validated.</typeparam>
/// <typeparam name="TProperty">The type of the specific property on the instance that the rule applies to.</typeparam>
internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TRequest>, IRuleBuilder<TRequest, TProperty>
{
private readonly Func<TRequest, TProperty> _propertySelector;
// Predicates and their errors are kept in two parallel lists (rather than a single list of tuples)
// so that Must() can append cheaply and WithError() can patch the *last* entry by index, without
// having to rebuild a composite struct each time.
private readonly List<Func<TProperty, bool>> _predicates = [];
private readonly List<Error> _predicateErrors = [];
// instance-aware predicates get their own separate pair of lists instead of being merged into the
// lists above, because they have a different delegate signature (TRequest, TProperty) vs (TProperty).
// Keeping them separate avoids wrapping every plain predicate in an adapter, just to fit one shape.
private readonly List<Func<TRequest, TProperty, bool>> _instanceAwarePredicates = [];
private readonly List<Error> _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func<TRequest, bool>? condition;
// Tracks which list WithError() should patch, since it doesn't know on its own whether the
// most recent Must() call went to the plain-predicate list or the instance-aware list.
private bool lastAddedPredicateIsInstanceAware;
private AbstractValidator<TProperty>? _childValidator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRule{TRequest, TProperty}"/> class.
/// </summary>
/// <param name="propertySelector">A function that extracts the property value from the request instance.</param>
public ValidationRule(Func<TRequest, TProperty> propertySelector)
{
_propertySelector = propertySelector;
}
/// <summary>
/// Adds a condition that the property must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> Must(Func<TProperty, bool> predicate)
{
_predicates.Add(predicate);
// Every predicate is paired with whatever error is "current" at the time it's added, so that a
// subsequent WithError() call has something concrete to overwrite via index lookup.
_predicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = false;
return this;
}
/// <summary>
/// Adds a condition that the request instance together with the property must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with the property value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> Must(Func<TRequest, TProperty, bool> predicate)
{
// This overload exists for cross-field rules (e.g. "EndDate must be after StartDate") where
// the check can't be expressed from the property value alone and needs the whole request.
_instanceAwarePredicates.Add(predicate);
_instanceAwarePredicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = true;
return this;
}
/// <summary>
/// Specifies a condition that must be met for the validation rule to be executed.
/// </summary>
/// <param name="condition">A function evaluating the request instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> When(Func<TRequest, bool> condition)
{
this.condition = condition;
return this;
}
/// <summary>
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
/// </summary>
/// <param name="error">The specific error to return upon failure.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> WithError(Error error)
{
// Callers might pass in an error created with the wrong factory (e.g. Error.NotFound()) by mistake.
// Rebuilding it as Error.Validation() here guarantees every error surfaced by this class is
// consistently typed as a validation error, regardless of what the caller supplied.
Error validationError = Error.Validation(description: error.Description);
currentError = validationError;
// WithError() is meant to apply to the predicate that was *just* added via Must(), not to all
// predicates registered so far. Since Must() can target either parallel-list pair, we use the
// flag set by the last Must() call to figure out which list's last slot to overwrite.
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
_instanceAwarePredicateErrors[^1] = validationError;
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
_predicateErrors[^1] = validationError;
return this;
}
/// <summary>
/// Defines nested validation rules for the complex property being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for the property.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> ChildRules(Action<AbstractValidator<TProperty>> configure)
{
// Lets a rule delegate to a fully separate validator for a complex nested object (e.g. validating
// an Address property's own fields) instead of forcing every nested check to be flattened into
// Must() predicates on this rule.
InlineValidator<TProperty> childValidator = new();
configure(childValidator);
_childValidator = childValidator;
return this;
}
/// <summary>
/// Evaluates all configured predicates against the specified request instance.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>The <see cref="Error"/> of every predicate that fails; empty if the rule passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// evaluate the condition first, if it returns false, skip validation entirely.
if (condition is not null && !condition(instance))
yield break;
TProperty value = _propertySelector(instance);
// Deliberately does NOT stop at the first failure: every failing predicate contributes its own error,
// so a caller sees the full set of problems for // this property in one pass instead of having to fix
// and resubmit one error at a time.
for (int index = 0; index < _predicates.Count; index++)
if (!_predicates[index](value))
yield return _predicateErrors[index];
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
if (!_instanceAwarePredicates[index](instance, value))
yield return _instanceAwarePredicateErrors[index];
if (_childValidator is not null && value is not null)
foreach (Error childError in _childValidator.Validate(value))
yield return childError;
}
}
@@ -0,0 +1,132 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Web.Common.Validation;
/// <summary>
/// Defines a validation rule that evaluates each item within a collection property of an instance.
/// </summary>
/// <typeparam name="TRequest">The type of the instance being validated.</typeparam>
/// <typeparam name="TItem">The type of the items in the collection that the rule applies to.</typeparam>
internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<TRequest>, IRuleBuilder<TRequest, TItem>
{
private readonly Func<TRequest, IEnumerable<TItem>?> _collectionSelector;
private readonly List<Func<TItem, bool>> _predicates = [];
private readonly List<Error> _predicateErrors = [];
private readonly List<Func<TRequest, TItem, bool>> _instanceAwarePredicates = [];
private readonly List<Error> _instanceAwarePredicateErrors = [];
private Error currentError = Error.Validation();
private Func<TRequest, bool>? condition;
private bool lastAddedPredicateIsInstanceAware;
private AbstractValidator<TItem>? _childValidator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationRuleForEach{TRequest, TItem}"/> class.
/// </summary>
/// <param name="collectionSelector">A function that extracts the collection to iterate from the request instance.</param>
public ValidationRuleForEach(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
{
_collectionSelector = collectionSelector;
}
/// <summary>
/// Adds a condition that each item in the collection must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test each item value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> Must(Func<TItem, bool> predicate)
{
_predicates.Add(predicate);
_predicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = false;
return this;
}
/// <summary>
/// Adds a condition that the request instance together with each item must satisfy to be considered valid.
/// </summary>
/// <param name="predicate">A function to test the request instance together with each item value.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> Must(Func<TRequest, TItem, bool> predicate)
{
_instanceAwarePredicates.Add(predicate);
_instanceAwarePredicateErrors.Add(currentError);
lastAddedPredicateIsInstanceAware = true;
return this;
}
/// <summary>
/// Specifies a condition that must be met for the validation rule to be executed.
/// </summary>
/// <param name="condition">A function evaluating the request instance.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> When(Func<TRequest, bool> condition)
{
this.condition = condition;
return this;
}
/// <summary>
/// Specifies a custom <see cref="Error"/> object to be returned when the validation fails.
/// </summary>
/// <param name="error">The specific error to return upon failure.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> WithError(Error error)
{
// validation rules always produce validation errors, regardless of the error type of the source error
Error validationError = Error.Validation(description: error.Description);
currentError = validationError;
if (lastAddedPredicateIsInstanceAware && _instanceAwarePredicateErrors.Count > 0)
_instanceAwarePredicateErrors[^1] = validationError;
else if (!lastAddedPredicateIsInstanceAware && _predicateErrors.Count > 0)
_predicateErrors[^1] = validationError;
return this;
}
/// <summary>
/// Defines nested validation rules for each item of the collection being validated.
/// </summary>
/// <param name="configure">An action used to configure the inline validator for each item.</param>
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> ChildRules(Action<AbstractValidator<TItem>> configure)
{
InlineValidator<TItem> childValidator = new();
configure(childValidator);
_childValidator = childValidator;
return this;
}
/// <summary>
/// Evaluates all configured predicates against each item in the collection.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>One <see cref="Error"/> per failing predicate, per item; empty if every item passes.</returns>
public IEnumerable<Error> Validate(TRequest instance)
{
// evaluate the condition first, if it returns false, skip validation entirely.
if (condition is not null && !condition(instance))
yield break;
IEnumerable<TItem>? collection = _collectionSelector(instance);
if (collection is null)
yield break;
foreach (TItem item in collection)
{
for (int index = 0; index < _predicates.Count; index++)
if (!_predicates[index](item))
yield return _predicateErrors[index];
for (int index = 0; index < _instanceAwarePredicates.Count; index++)
if (!_instanceAwarePredicates[index](instance, item))
yield return _instanceAwarePredicateErrors[index];
if (_childValidator is not null && item is not null)
foreach (Error childError in _childValidator.Validate(item))
yield return childError;
}
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Utilities;
using Lumina.Presentation.Web.Common.Validation;
using System;
using System.Buffers.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
/// </summary>
public class EncryptionSettingsDtoValidator : AbstractValidator<EncryptionSettingsDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsDtoValidator"/> class.
/// </summary>
public EncryptionSettingsDtoValidator()
{
RuleFor(settings => settings.SecretKey)
.NotEmpty()
.WithError(Error.Validation(description: "Encryption secret key cannot be empty!"))
.Must(secretKey => Base64.IsValid(secretKey.AsSpan()))
.WithError(Error.Validation(description: "Encryption secret key must be a base64 string!"));
}
}
@@ -1,24 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using System;
using System.Buffers.Text;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
/// </summary>
public class EncryptionSettingsModelValidator : AbstractValidator<EncryptionSettingsDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidator"/> class.
/// </summary>
public EncryptionSettingsModelValidator()
{
RuleFor(x => x.SecretKey)
.NotEmpty().WithMessage("Encryption secret key cannot be empty!")
.Must(value => Base64.IsValid(value.AsSpan())).WithMessage("Encryption secret key must be a base64 string!");
}
}
@@ -0,0 +1,32 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Utilities;
using Lumina.Presentation.Web.Common.Validation;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the ServerConfiguration application configuration settings section.
/// </summary>
public class ServerConfigurationDtoValidator : AbstractValidator<ServerConfigurationDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="ServerConfigurationDtoValidator"/> class.
/// </summary>
public ServerConfigurationDtoValidator()
{
RuleFor(configuration => configuration.BaseAddress)
.NotEmpty()
.WithError(Error.Validation(description: "Base address cannot be empty!"));
RuleFor(configuration => configuration.Port)
.InclusiveBetween((ushort)0, (ushort)65535)
.WithError(Error.Validation(description: "Port number must be between 0 and 65535!"));
RuleFor(configuration => configuration.ApiVersion)
.InclusiveBetween((char)0, (char)255)
.WithError(Error.Validation(description: "API version must be between 0 and 255!"));
}
}
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.DTO.Configuration;
#endregion
namespace Lumina.Presentation.Web.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the ServerConfiguration application configuration settings section.
/// </summary>
public class ServerConfigurationModelValidator : AbstractValidator<ServerConfigurationDto>
{
/// <summary>
/// Initializes a new instance of the <see cref="ServerConfigurationModelValidator"/> class.
/// </summary>
public ServerConfigurationModelValidator()
{
RuleFor(x => x.BaseAddress).NotEmpty().WithMessage("Base address cannot be empty!");
RuleFor(x => x.Port).InclusiveBetween((ushort)0, (ushort)65535).WithMessage("Port number must be between 0 and 65535!");
RuleFor(x => x.ApiVersion).InclusiveBetween((char)0, (char)255).WithMessage("API version must be between 0 and 255!");
}
}
@@ -21,8 +21,6 @@
<ItemGroup>
<PackageReference Include="FastEndpoints" Version="8.2.0" />
<PackageReference Include="FastEndpoints.Swagger" Version="8.2.0" />
<PackageReference Include="FluentValidation" Version="12.1.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.11" />
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="10.9.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="10.0.11" />
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validation;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Setup;
/// <summary>
/// Validator extension methods for <see cref="IValidator{TRequest}"/> for unit tests.
/// </summary>
[ExcludeFromCodeCoverage]
public static class ValidatorTestExtensions
{
/// <summary>
/// Executes the validator against the specified request instance and returns the resulting errors.
/// </summary>
/// <typeparam name="TRequest">The type of the request being validated.</typeparam>
/// <param name="validator">The validator instance to execute.</param>
/// <param name="request">The request instance to validate.</param>
/// <returns>A list of <see cref="Error"/> produced by the validator. If the request is valid, the list will be empty.</returns>
public static List<Error> TestValidate<TRequest>(this IValidator<TRequest> validator, TRequest request)
{
return validator.Validate(request);
}
/// <summary>
/// Asserts that the validation results do not contain the specified error.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
/// <param name="expectedError">The error that should not be present in the validation results.</param>
public static void ShouldNotHaveValidationError(this List<Error> errors, Error expectedError)
{
Assert.DoesNotContain(errors, error => error.Description == expectedError.Description);
}
/// <summary>
/// Asserts that the validation results contain the specified error.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
/// <param name="expectedError">The error that should be present in the validation results.</param>
public static void ShouldHaveValidationError(this List<Error> errors, Error expectedError)
{
Assert.Contains(errors, error => error.Description == expectedError.Description);
}
/// <summary>
/// Asserts that the validation results are completely empty, indicating the request is valid.
/// </summary>
/// <param name="errors">The list of errors returned by the validator.</param>
public static void ShouldNotHaveAnyValidationErrors(this List<Error> errors)
{
Assert.Empty(errors);
}
}
@@ -1,21 +1,22 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using FluentValidation.Results;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validators;
using Lumina.Presentation.Web.UnitTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="EncryptionSettingsModelValidator"/> class.
/// Contains unit tests for the <see cref="EncryptionSettingsDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class EncryptionSettingsModelValidatorTests
{
private const string VALID_BASE64_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM=";
private readonly EncryptionSettingsModelValidator _validator = new();
private readonly EncryptionSettingsDtoValidator _validator = new();
[Fact]
public void Validate_WhenSecretKeyIsEmpty_ShouldHaveValidationError()
@@ -24,11 +25,10 @@ public class EncryptionSettingsModelValidatorTests
EncryptionSettingsDto settings = new() { SecretKey = string.Empty };
// Act
ValidationResult result = _validator.Validate(settings);
List<Error> result = _validator.TestValidate(settings);
// Assert
Assert.False(result.IsValid);
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key cannot be empty!");
result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key cannot be empty!"));
}
[Fact]
@@ -38,11 +38,10 @@ public class EncryptionSettingsModelValidatorTests
EncryptionSettingsDto settings = new() { SecretKey = "not-base64-key!" };
// Act
ValidationResult result = _validator.Validate(settings);
List<Error> result = _validator.TestValidate(settings);
// Assert
Assert.False(result.IsValid);
Assert.Contains(result.Errors, error => error.PropertyName == nameof(EncryptionSettingsDto.SecretKey) && error.ErrorMessage == "Encryption secret key must be a base64 string!");
result.ShouldHaveValidationError(Error.Validation(description: "Encryption secret key must be a base64 string!"));
}
[Fact]
@@ -52,9 +51,9 @@ public class EncryptionSettingsModelValidatorTests
EncryptionSettingsDto settings = new() { SecretKey = VALID_BASE64_KEY };
// Act
ValidationResult result = _validator.Validate(settings);
List<Error> result = _validator.TestValidate(settings);
// Assert
Assert.True(result.IsValid);
result.ShouldNotHaveAnyValidationErrors();
}
}
@@ -1,20 +1,21 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using FluentValidation.Results;
using Lumina.Presentation.Web.Common.DTO.Configuration;
using Lumina.Presentation.Web.Common.Primitives;
using Lumina.Presentation.Web.Common.Validators;
using Lumina.Presentation.Web.UnitTests.Common.Setup;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.UnitTests.Common.Validators;
/// <summary>
/// Contains unit tests for the <see cref="ServerConfigurationModelValidator"/> class.
/// Contains unit tests for the <see cref="ServerConfigurationDtoValidator"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ServerConfigurationModelValidatorTests
{
private readonly ServerConfigurationModelValidator _validator = new();
private readonly ServerConfigurationDtoValidator _validator = new();
[Fact]
public void Validate_WhenBaseAddressIsEmpty_ShouldHaveValidationError()
@@ -23,11 +24,10 @@ public class ServerConfigurationModelValidatorTests
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = string.Empty, Port = 5214 };
// Act
ValidationResult result = _validator.Validate(configuration);
List<Error> result = _validator.TestValidate(configuration);
// Assert
Assert.False(result.IsValid);
Assert.Contains(result.Errors, error => error.PropertyName == nameof(ServerConfigurationDto.BaseAddress) && error.ErrorMessage == "Base address cannot be empty!");
result.ShouldHaveValidationError(Error.Validation(description: "Base address cannot be empty!"));
}
[Theory]
@@ -39,10 +39,10 @@ public class ServerConfigurationModelValidatorTests
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = port };
// Act
ValidationResult result = _validator.Validate(configuration);
List<Error> result = _validator.TestValidate(configuration);
// Assert
Assert.True(result.IsValid);
result.ShouldNotHaveAnyValidationErrors();
}
[Theory]
@@ -54,10 +54,10 @@ public class ServerConfigurationModelValidatorTests
ServerConfigurationDto configuration = new() { ApiVersion = apiVersion, BaseAddress = "http://localhost", Port = 5214 };
// Act
ValidationResult result = _validator.Validate(configuration);
List<Error> result = _validator.TestValidate(configuration);
// Assert
Assert.True(result.IsValid);
result.ShouldNotHaveAnyValidationErrors();
}
[Fact]
@@ -67,9 +67,9 @@ public class ServerConfigurationModelValidatorTests
ServerConfigurationDto configuration = new() { ApiVersion = '1', BaseAddress = "http://localhost", Port = 5214 };
// Act
ValidationResult result = _validator.Validate(configuration);
List<Error> result = _validator.TestValidate(configuration);
// Assert
Assert.True(result.IsValid);
result.ShouldNotHaveAnyValidationErrors();
}
}