when function
IValidator
when(
- IValidator condition, {
- required IValidator then,
- required IValidator otherwise,
- String? message,
Creates a conditional validator. It's conditional based on some other field in the eskema.
The condition validator is run against the parent map.
- If the condition is met,
thenis used to validate the current field's value. - If the condition is not met,
otherwiseis used.
Usage Examples:
// Conditional validation based on user type
final userValidator = eskema({
'userType': $isString,
'permissions': when(
isEq('admin'), // Condition: if userType is 'admin'
isList(), // Then: permissions must be a list
isEq(null), // Otherwise: permissions must be null
),
});
// Age-based validation
final personValidator = eskema({
'age': $isInt,
'licenseNumber': when(
isGte(18), // Condition: if age >= 18
stringLength([isEq(8)]), // Then: license must be 8 characters
isEq(null), // Otherwise: license must be null
),
});
// Complex conditional logic
final paymentValidator = eskema({
'method': $isString,
'cardNumber': when(
isEq('credit_card'), // If payment method is credit card
stringMatchesPattern(r'^\d{16}$'), // Then: validate 16-digit card number
isEq(null), // Otherwise: card number should be null
),
});
Implementation
IValidator when(
IValidator condition, {
required IValidator then,
required IValidator otherwise,
String? message,
}) {
final base = WhenValidator(condition: condition, then: then, otherwise: otherwise);
// Wrap with a proxy that intercepts misuse (validate()) and parent usage (validateWithParent)
return message == null ? base : WhenWithMessage(base, message);
}