stringMatchesPattern function

IValidator stringMatchesPattern(
  1. Pattern pattern, {
  2. String? message,
})

Validates that the String matches the provided pattern

This validator also validates that the value is a String first So there's no need to add the isString validator when using this validator

Usage Examples:

// Validate phone number format
final phonePattern = stringMatchesPattern(r'^\+?[\d\s\-\(\)]+$');
phonePattern.validate("+1-555-0123");     // Valid
phonePattern.validate("invalid-phone");    // Invalid

// Validate hexadecimal color
final hexColor = stringMatchesPattern(r'^#[0-9A-Fa-f]{6}$');
hexColor.validate("#FF5733");              // Valid
hexColor.validate("#GGG");                 // Invalid

// Custom error message
final customPattern = stringMatchesPattern(r'^\d{4}-\d{2}-\d{2}$',
  message: 'Date must be in YYYY-MM-DD format');

Implementation

IValidator stringMatchesPattern(Pattern pattern, {String? message}) {
  return isType<String>() &
      validator(
        (value) => pattern.allMatches(value).isNotEmpty,
        (value) => Expectation(
          message: message ?? 'String to match "$pattern"',
          value: value,
          code: ExpectationCodes.valuePatternMismatch,
          data: {'pattern': pattern.toString()},
        ),
      );
}