Class PredicateValidator<T>
- Namespace
- SteamNetworkLib.Sync
- Assembly
- SteamNetworkLib.dll
Base class for simple validators using a predicate function.
public class PredicateValidator<T> : ISyncValidator<T>
Type Parameters
TThe type of value to validate.
- Inheritance
-
PredicateValidator<T>
- Implements
- Inherited Members
Remarks
Best For: One-off custom validation logic without creating a dedicated validator class.
Performance: The predicate is invoked directly without additional overhead.
// Validate that a string is not empty and has valid length
var usernameValidator = new PredicateValidator<string>(
username => !string.IsNullOrWhiteSpace(username) && username.Length >= 3 && username.Length <= 20,
"Username must be 3-20 characters and not whitespace"
);
// Validate enum is defined
var gameModeValidator = new PredicateValidator<GameMode>(
mode => Enum.IsDefined(typeof(GameMode), mode),
"Invalid game mode selected"
);
Constructors
PredicateValidator(Func<T, bool>, string)
Creates a new predicate-based validator.
public PredicateValidator(Func<T, bool> predicate, string errorMessage)
Parameters
predicateFunc<T, bool>Function that returns true if the value is valid.
errorMessagestringError message to return when validation fails.
Remarks
The predicate should be pure (no side effects) as it may be called multiple times.
The error message should clearly explain what validation failed for debugging purposes.
Exceptions
- ArgumentNullException
Thrown when predicate 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.