83 lines
2.9 KiB
C#
83 lines
2.9 KiB
C#
namespace StellaOps.DependencyInjection.Validation;
|
|
|
|
public abstract partial class OptionsValidatorBase<TOptions>
|
|
where TOptions : class
|
|
{
|
|
/// <summary>
|
|
/// Provides a fluent interface for collecting validation errors.
|
|
/// </summary>
|
|
protected sealed partial class ValidationContext
|
|
{
|
|
private readonly List<string> _errors = new();
|
|
private readonly string _sectionPrefix;
|
|
|
|
internal ValidationContext(string sectionPrefix)
|
|
{
|
|
_sectionPrefix = sectionPrefix;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the collected errors.
|
|
/// </summary>
|
|
public IReadOnlyList<string> Errors => _errors;
|
|
|
|
/// <summary>
|
|
/// Returns true if any errors have been added.
|
|
/// </summary>
|
|
public bool HasErrors => _errors.Count > 0;
|
|
|
|
/// <summary>
|
|
/// Adds a validation error for a specific property.
|
|
/// </summary>
|
|
/// <param name="propertyName">The property name (e.g., "MaxRetries").</param>
|
|
/// <param name="message">The error message.</param>
|
|
/// <returns>This context for chaining.</returns>
|
|
public ValidationContext AddError(string propertyName, string message)
|
|
{
|
|
_errors.Add($"{_sectionPrefix}:{propertyName} {message}");
|
|
return this;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a validation error for a nested property.
|
|
/// </summary>
|
|
/// <param name="parentProperty">The parent property name.</param>
|
|
/// <param name="childProperty">The child property name.</param>
|
|
/// <param name="message">The error message.</param>
|
|
/// <returns>This context for chaining.</returns>
|
|
public ValidationContext AddError(string parentProperty, string childProperty, string message)
|
|
{
|
|
_errors.Add($"{_sectionPrefix}:{parentProperty}:{childProperty} {message}");
|
|
return this;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a general validation error.
|
|
/// </summary>
|
|
/// <param name="message">The error message.</param>
|
|
/// <returns>This context for chaining.</returns>
|
|
public ValidationContext AddGeneralError(string message)
|
|
{
|
|
_errors.Add($"{_sectionPrefix}: {message}");
|
|
return this;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Conditionally adds an error if the condition is true.
|
|
/// </summary>
|
|
/// <param name="condition">The condition to check.</param>
|
|
/// <param name="propertyName">The property name.</param>
|
|
/// <param name="message">The error message.</param>
|
|
/// <returns>This context for chaining.</returns>
|
|
public ValidationContext AddErrorIf(bool condition, string propertyName, string message)
|
|
{
|
|
if (condition)
|
|
{
|
|
AddError(propertyName, message);
|
|
}
|
|
|
|
return this;
|
|
}
|
|
}
|
|
}
|