Replaces FluentValidation with the custom validation framework in the web project

This commit is contained in:
BinaryAlley committed 2026-08-19 10:25:28 -07:00
1 parent 587daaabb7
commit 57e8e2ed65
19 files changed
+1020 -104

No files matched your search

@@ -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;
}
}
}