Class CompositeValidator<T>
- Namespace
- SteamNetworkLib.Sync
- Assembly
- SteamNetworkLib.dll
Validator that combines multiple validators with AND logic.
public class CompositeValidator<T> : ISyncValidator<T>
Type Parameters
TThe type of value to validate.
- Inheritance
-
CompositeValidator<T>
- Implements
- Inherited Members
Remarks
Validation Logic: All validators must pass for the value to be considered valid. Validators are checked in order, and the first failure determines the error message.
Use Cases:
- Combining range validation with custom business rules
- Validating multiple independent constraints
- Reusing existing validators in complex validation scenarios
Performance: Validators are evaluated sequentially. Order validators from fastest to slowest for optimal performance (fail fast on cheap checks).
// Combine range and custom validation
var healthValidator = new CompositeValidator<int>(
new RangeValidator<int>(0, 100),
new PredicateValidator<int>(
health => health % 10 == 0,
"Health must be a multiple of 10"
)
);
// Multiple string constraints
var usernameValidator = new CompositeValidator<string>(
new PredicateValidator<string>(
s => !string.IsNullOrWhiteSpace(s),
"Username cannot be empty"
),
new PredicateValidator<string>(
s => s.Length >= 3 && s.Length <= 20,
"Username must be 3-20 characters"
),
new PredicateValidator<string>(
s => s.All(char.IsLetterOrDigit),
"Username must be alphanumeric"
)
);
Constructors
CompositeValidator(params ISyncValidator<T>[])
Initializes a new instance of the CompositeValidator<T> class.
public CompositeValidator(params ISyncValidator<T>[] validators)
Parameters
validatorsISyncValidator<T>[]Array of validators to check. All must pass for validation to succeed.
Remarks
Validators are evaluated in the order provided.
The error message from the first failing validator is returned.
If no validators are provided, all values pass validation.
Exceptions
- ArgumentNullException
Thrown when validators array is null.
Methods
GetErrorMessage(T)
Gets a human-readable error message describing why validation failed.
public string? GetErrorMessage(T value)
Parameters
valueTThe invalid value that failed validation.
Returns
- string
An error message describing why the value is invalid, or null if no specific message is available.
Remarks
This message is used in SyncValidationException and logged when validation fails.
Include the invalid value and expected constraints in the message for easier debugging.
IsValid(T)
Validates a value before it is synchronized.
public bool IsValid(T value)
Parameters
valueTThe value to validate.
Returns
- bool
True if the value is valid and should be synchronized; false otherwise.
Remarks
This method is called synchronously before each sync operation.
Keep validation logic fast and non-blocking as it runs on the main thread.