Class PredicateValidatorRule<T, TProperty>
A validation rule that uses a predicate function to validate a property of an entity. Supports lambda expressions for concise rule definitions.
public class PredicateValidatorRule<T, TProperty> : IValidatorRuleSync<T>, IValidatorRule<T>
Type Parameters
TThe type of entity to validate.
TPropertyThe type of the property being validated.
- Inheritance
-
PredicateValidatorRule<T, TProperty>
- Implements
- Inherited Members
- Extension Methods
Examples
// Create a rule using lambda
var rule = new PredicateValidatorRule<User, string>(
u => u.Email,
"EmailRequired",
"Email is required",
email => !string.IsNullOrEmpty(email)
);
// Use the rule
var result = rule.Validate(user);
Constructors
PredicateValidatorRule(Func<T, TProperty>, string, string, Func<TProperty, bool>)
Initializes a new instance of the PredicateValidatorRule.
public PredicateValidatorRule(Func<T, TProperty> propertySelector, string ruleName, string errorMessage, Func<TProperty, 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, bool>The validation predicate function.
Examples
var rule = new PredicateValidatorRule<User, string>(
u => u.Email,
"EmailRequired",
"Email is required",
email => !string.IsNullOrEmpty(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
Validate(T)
Validates the specified entity using the predicate function.
public ValidationResult<T> Validate(T entity)
Parameters
entityTThe entity to validate.
Returns
- ValidationResult<T>
A ValidationResult indicating success or failure.
Examples
var user = new User("", 25);
var result = rule.Validate(user);
if (result.IsValid)
{
Console.WriteLine("Validation passed");
}
else
{
Console.WriteLine($"Validation failed: {result.ValidationErrors.First().Message}");
}