Class AsyncPredicateValidatorRule<T, TProperty>
A validation rule that uses an async predicate function to validate a property of an entity. Supports async lambda expressions for asynchronous validation scenarios.
public class AsyncPredicateValidatorRule<T, TProperty> : IValidatorRuleAsync<T>, IValidatorRule<T>
Type Parameters
TThe type of entity to validate.
TPropertyThe type of the property being validated.
- Inheritance
-
AsyncPredicateValidatorRule<T, TProperty>
- Implements
- Inherited Members
- Extension Methods
Examples
// Create an async rule using lambda
var rule = new AsyncPredicateValidatorRule<User, string>(
u => u.Email,
"UniqueEmail",
"Email already exists",
async email => await EmailService.IsUniqueAsync(email)
);
// Use the rule
var result = await rule.ValidateAsync(user);
Constructors
AsyncPredicateValidatorRule(Func<T, TProperty>, string, string, Func<TProperty, Task<bool>>)
Initializes a new instance of the AsyncPredicateValidatorRule.
public AsyncPredicateValidatorRule(Func<T, TProperty> propertySelector, string ruleName, string errorMessage, Func<TProperty, Task<bool>> validator)
Parameters
propertySelectorFunc<T, TProperty>Function to select the property to validate.
ruleNamestringThe name of the validation rule.
errorMessagestringThe error message if validation fails.
validatorFunc<TProperty, Task<bool>>The async validation predicate function.
Examples
var rule = new AsyncPredicateValidatorRule<User, string>(
u => u.Email,
"UniqueEmail",
"Email already exists",
async email => await EmailService.IsUniqueAsync(email)
);
Properties
ErrorMessage
Gets the default error message for this validation rule.
public string ErrorMessage { get; }
Property Value
Name
Gets the name of the validation rule.
public string Name { get; }
Property Value
Methods
ValidateAsync(T)
Validates the specified entity using the async predicate function.
public Task<ValidationResult<T>> ValidateAsync(T entity)
Parameters
entityTThe entity to validate.
Returns
- Task<ValidationResult<T>>
A ValidationResult indicating success or failure.
Examples
var user = new User("test@example.com", 25);
var result = await rule.ValidateAsync(user);
if (result.IsValid)
{
Console.WriteLine("Validation passed");
}
else
{
Console.WriteLine($"Validation failed: {result.ValidationErrors.First().Message}");
}