postalCode static method

String? postalCode(
  1. String? value, {
  2. String country = 'US',
})

Validates a postal/zip code.

Implementation

static String? postalCode(String? value, {String country = 'US'}) {
  if (value == null || value.isEmpty) return 'Postal code is required';

  final cleaned = value.toUpperCase().replaceAll(' ', '');

  switch (country) {
    case 'US':
      if (!RegExp(r'^\d{5}(-\d{4})?$').hasMatch(cleaned)) {
        return 'Invalid US zip code format';
      }
      break;
    case 'CA':
      if (!RegExp(r'^[A-Z]\d[A-Z]\d[A-Z]\d$').hasMatch(cleaned)) {
        return 'Invalid Canadian postal code format';
      }
      break;
    default:
      if (cleaned.length < 3) return 'Invalid postal code';
  }

  return null;
}