Replaces FluentValidation and Mediator command/queries handling with custom implementations.

This commit is contained in:
BinaryAlley committed 2026-08-13 08:53:06 -07:00
1 parent 9a5c7473f9
commit 2d1c6b1ab8
297 files changed
+3619 -3045

No files matched your search

@@ -1,53 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FluentValidation;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Common.Behaviors;
/// <summary>
/// Represents a validation behavior in the Mediator pipeline for handling requests and responses.
/// </summary>
/// <typeparam name="TRequest">The type representing a request. It should implement <see cref="IRequest{TResponse}"/>.</typeparam>
/// <typeparam name="TResponse">The type representing a response. It should implement <see cref="IErrorOr"/> interface.</typeparam>
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
where TResponse : IErrorOr
{
private readonly IValidator<TRequest>? _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ValidationBehavior{TRequest, TResponse}"/> class.
/// </summary>
/// <param name="validator">The validator used in this behavior pipeline for the Mediator commands and queries.</param>
public ValidationBehavior(IValidator<TRequest>? validator = null)
{
_validator = validator;
}
/// <summary>
/// Pipeline handler. Perform any additional behavior and await the <paramref name="next"/> delegate as necessary.
/// </summary>
/// <param name="request">Incoming request.</param>
/// <param name="next">Awaitable delegate for the next action in the pipeline. Eventually this delegate represents the handler.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask<TResponse> Handle(TRequest request, MessageHandlerDelegate<TRequest, TResponse> next, CancellationToken cancellationToken)
{
// if there is no validator, just invoke the handler
if (_validator is null)
return await next(request, cancellationToken).ConfigureAwait(false);
// before the handler of the command is executed
FluentValidation.Results.ValidationResult validationResult = await _validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false);
// if there are no validation errors, invoke the command handler
if (validationResult.IsValid)
return await next(request, cancellationToken).ConfigureAwait(false);
// after the command handler is executed
List<Error> errors = validationResult.Errors.ConvertAll(validationFailure => Error.Validation(description: validationFailure.ErrorMessage));
// the compiler doesn't know there is an implicit converter from a list of errors to the ErrorOr object, and unfortunately, there is no way around this but to use some magic
// this is acceptable because we DO know that we will always have a list of errors of type ErrorOr (check the generic constraint at the top of the class!)
return (dynamic)errors;
}
}
@@ -1,7 +1,4 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Behaviors;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
@@ -25,44 +22,39 @@ public static class ApplicationLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddApplicationLayerServices(this IServiceCollection services)
{
// register Mediator
// register the Mediator publisher used for publishing domain events
services.AddMediator(options =>
{
options.ServiceLifetime = ServiceLifetime.Scoped;
});
// register the validation behavior
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
// register fluent validators
services.AddValidatorsFromAssembly(typeof(ApplicationLayerServices).Assembly);
Type[] handlers =
Type[] handlerContractTypes =
[
typeof(CQRS.ICommandHandler<,>),
typeof(CQRS.IQueryHandler<,>),
typeof(Infrastructure.Validation.IValidator<>),
];
IEnumerable<Type> types = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => !type.IsInterface && !type.IsAbstract);
IEnumerable<Type> concreteTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(type => !type.IsInterface && !type.IsAbstract && !type.IsGenericTypeDefinition);
var registrations = types
.SelectMany(type => type.GetInterfaces(),
(implementation, service) => new { Service = service, Implmentation = implementation })
.Where(type => type.Service.IsGenericType && handlers.Contains(type.Service.GetGenericTypeDefinition()));
var handlerRegistrations = concreteTypes
.SelectMany(implementation => implementation.GetInterfaces(),
(implementation, contract) => new { Contract = contract, Implementation = implementation })
.Where(registration => registration.Contract.IsGenericType && handlerContractTypes.Contains(registration.Contract.GetGenericTypeDefinition()));
foreach (var registration in registrations)
foreach (var registration in handlerRegistrations)
{
if (!services.Any(service => service.ServiceType == registration.Service))
{
if (registration.Service.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
services.AddSingleton(registration.Service, registration.Implmentation);
else
services.AddScoped(registration.Service, registration.Implmentation);
}
if (services.Any(service => service.ServiceType == registration.Contract))
continue;
if (registration.Contract.GetGenericTypeDefinition() == typeof(Infrastructure.Validation.IValidator<>))
services.AddSingleton(registration.Contract, registration.Implementation);
else
services.AddScoped(registration.Contract, registration.Implementation);
}
return services;
}
}
@@ -20,7 +20,7 @@ public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
/// <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>
protected IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
public IRuleBuilder<TRequest, TProperty> RuleFor<TProperty>(Func<TRequest, TProperty> propertySelector)
{
ValidationRule<TRequest, TProperty> rule = new(propertySelector);
_rules.Add(rule);
@@ -33,7 +33,7 @@ public abstract class AbstractValidator<TRequest> : IValidator<TRequest>
/// <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>
protected IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
public IRuleBuilder<TRequest, TItem> RuleForEach<TItem>(Func<TRequest, IEnumerable<TItem>?> collectionSelector)
{
ValidationRuleForEach<TRequest, TItem> rule = new(collectionSelector);
_rules.Add(rule);
@@ -19,6 +19,13 @@ public interface IRuleBuilder<TRequest, TProperty>
/// <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>
@@ -32,4 +39,11 @@ public interface IRuleBuilder<TRequest, TProperty>
/// <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,12 @@
#region ========================================================================= USING =====================================================================================
#endregion
namespace Lumina.Application.Common.Infrastructure.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 request (command or query) to be validated.</typeparam>
public class InlineValidator<TRequest> : AbstractValidator<TRequest>
{
}
@@ -14,10 +14,28 @@ namespace Lumina.Application.Common.Infrastructure.Validation;
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 Error error = Error.Validation();
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>
@@ -35,6 +53,25 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
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;
}
@@ -56,7 +93,35 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
/// <returns>The current <see cref="IRuleBuilder{TRequest, TProperty}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TProperty> WithError(Error error)
{
this.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;
}
@@ -64,7 +129,7 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
/// Evaluates all configured predicates against the specified request instance.
/// </summary>
/// <param name="instance">The request instance to validate.</param>
/// <returns>The <see cref="Error"/> if any predicate fails; empty if the rule passes.</returns>
/// <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.
@@ -73,13 +138,19 @@ internal sealed class ValidationRule<TRequest, TProperty> : IValidationRule<TReq
TProperty value = _propertySelector(instance);
foreach (Func<TProperty, bool> predicate in _predicates)
{
if (!predicate(value))
{
yield return error;
yield break;
}
}
// 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;
}
}
@@ -15,8 +15,13 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
{
private readonly Func<TRequest, IEnumerable<TItem>?> _collectionSelector;
private readonly List<Func<TItem, bool>> _predicates = [];
private Error error = Error.Validation();
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.
@@ -35,6 +40,21 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
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;
}
@@ -56,7 +76,26 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
/// <returns>The current <see cref="IRuleBuilder{TRequest, TItem}"/> instance for method chaining.</returns>
public IRuleBuilder<TRequest, TItem> WithError(Error error)
{
this.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;
}
@@ -64,7 +103,7 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
/// 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 item that fails a predicate; empty if every item passes.</returns>
/// <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.
@@ -77,14 +116,17 @@ internal sealed class ValidationRuleForEach<TRequest, TItem> : IValidationRule<T
foreach (TItem item in collection)
{
foreach (Func<TItem, bool> predicate in _predicates)
{
if (!predicate(item))
{
yield return error;
break;
}
}
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;
}
}
}
@@ -1,7 +1,8 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Application.Common.Utilities;
@@ -38,6 +39,33 @@ public static class ValidatorUtilities
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>
@@ -50,13 +78,54 @@ public static class ValidatorUtilities
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}(IRuleBuilder{TRequest, string})"/> or
/// <see cref="NotEmpty{TRequest, TItem}(IRuleBuilder{TRequest, List{TItem}})"/> to also reject empty values.
/// <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>
@@ -68,43 +137,27 @@ public static class ValidatorUtilities
}
/// <summary>
/// Defines a validation rule that ensures the string property is not empty or consisting only of white-space characters.
/// Defines a validation rule that ensures the property is not empty.
/// </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).
/// 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, string> NotEmpty<TRequest>(this IRuleBuilder<TRequest, string> ruleBuilder)
public static IRuleBuilder<TRequest, TProperty> NotEmpty<TRequest, TProperty>(this IRuleBuilder<TRequest, TProperty> ruleBuilder)
{
return ruleBuilder.Must(value => value is null || value.Trim().Length > 0);
}
/// <summary>
/// Defines a validation rule that ensures the List property is not empty.
/// </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>
/// <typeparam name="TItem">The type of the items in the list 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, List<TItem>> NotEmpty<TRequest, TItem>(this IRuleBuilder<TRequest, List<TItem>> ruleBuilder)
{
return ruleBuilder.Must(value => value is null || value.Count > 0);
}
/// <summary>
/// Defines a validation rule that ensures the <see cref="Guid"/> property is not <see cref="Guid.Empty"/>.
/// </summary>
/// <typeparam name="TRequest">The type of the request 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, Guid> NotEmpty<TRequest>(this IRuleBuilder<TRequest, Guid> ruleBuilder)
{
return ruleBuilder.Must(value => value != Guid.Empty);
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>
@@ -130,4 +183,144 @@ public static class ValidatorUtilities
{
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 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)));
}
}