postcode_checker
A comprehensive Dart package for validating postal codes from countries worldwide using ISO 3166-1 alpha-2 country codes and CLDR-based regex patterns.
Features
- โ Comprehensive Coverage: Supports 170+ countries and territories
- ๐ ISO 3166-1 Standard: Uses official alpha-2 country codes
- ๐ฏ CLDR-Based Patterns: Regex patterns from Unicode CLDR v26.0.1
- ๐ Simple Static API: Clean, no-instantiation design
- ๐จ Type-Safe Error Handling: Enum-based error types with clear messages
- ๐ฆ Zero Dependencies: No external dependencies required
- ๐งช Well Tested: Comprehensive unit test coverage
- ๐ Well Documented: Clear examples and API documentation
Installation
Add this to your package's pubspec.yaml file:
dependencies:
postcode_checker: ^1.0.2
Then run:
dart pub get
Usage
Basic Validation
import 'package:postcode_checker/postcode_checker.dart';
void main() {
// Validate a US ZIP code
final usResult = PostcodeChecker.validate(CountryCode.US, '12345');
print(usResult.isValid); // true
// Validate a UK postcode
final ukResult = PostcodeChecker.validate(CountryCode.GB, 'SW1A 1AA');
print(ukResult.isValid); // true
// Validate an invalid postal code
final invalidResult = PostcodeChecker.validate(CountryCode.US, 'INVALID');
print(invalidResult.isValid); // false
print(invalidResult.errorMessage); // Error description
}
Working with Validation Results
final result = PostcodeChecker.validate(CountryCode.CA, 'K1A 0B1');
if (result.isValid) {
print('Valid postal code for ${result.countryCode.code}');
} else {
print('Invalid: ${result.errorMessage}');
}
Error Handling
The package provides type-safe error handling with clear error messages:
// Empty postal code error
final emptyResult = PostcodeChecker.validate(CountryCode.US, '');
print(emptyResult.error); // PostcodeValidationError.emptyPostalCode
print(emptyResult.errorCode); // 'EMPTY_POSTAL_CODE'
print(emptyResult.errorMessage); // 'Postal code cannot be empty or contain only whitespace.'
// Invalid format error
final invalidResult = PostcodeChecker.validate(CountryCode.US, 'ABC');
print(invalidResult.error); // PostcodeValidationError.invalidFormat
print(invalidResult.errorCode); // 'INVALID_FORMAT'
print(invalidResult.errorMessage); // 'The postal code does not match the expected format for this country.'
// No postal code system error
final noSystemResult = PostcodeChecker.validate(CountryCode.AO, '12345');
print(noSystemResult.error); // PostcodeValidationError.noPostalCodeSystem
print(noSystemResult.errorCode); // 'NO_POSTAL_CODE_SYSTEM'
Available error types:
PostcodeValidationError.emptyPostalCode- Empty or whitespace-only inputPostcodeValidationError.invalidFormat- Postal code doesn't match country patternPostcodeValidationError.noPostalCodeSystem- Country doesn't use postal codesPostcodeValidationError.unsupportedCountry- Country code not recognized
Check if a Country Has Postal Codes
print(PostcodeChecker.hasPostalCodes(CountryCode.US)); // true
print(PostcodeChecker.hasPostalCodes(CountryCode.GB)); // true
print(PostcodeChecker.hasPostalCodes(CountryCode.AO)); // false (Angola has no postal codes)
Get Postal Code Pattern
final pattern = PostcodeChecker.getPostalCodePattern(CountryCode.US);
print(pattern); // \d{5}([ \-]\d{4})?
final caPattern = PostcodeChecker.getPostalCodePattern(CountryCode.CA);
print(caPattern); // [ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ ]?\d[ABCEGHJ-NPRSTV-Z]\d
List Supported Countries
final countries = PostcodeChecker.supportedCountries();
print('Supported countries: ${countries.length}');
for (final country in countries.take(5)) {
print(country.code);
}
Supported Countries
This package supports postal code validation for 170+ countries and territories, including:
North America
- ๐บ๐ธ United States (US)
- ๐จ๐ฆ Canada (CA)
- ๐ฒ๐ฝ Mexico (MX)
- ๐ต๐ท Puerto Rico (PR)
Europe
- ๐ฌ๐ง United Kingdom (GB)
- ๐ฉ๐ช Germany (DE)
- ๐ซ๐ท France (FR)
- ๐ฎ๐น Italy (IT)
- ๐ช๐ธ Spain (ES)
- ๐ณ๐ฑ Netherlands (NL)
- ๐ต๐ฑ Poland (PL)
- ๐ธ๐ช Sweden (SE)
- And many more...
Asia-Pacific
- ๐ฏ๐ต Japan (JP)
- ๐จ๐ณ China (CN)
- ๐ฎ๐ณ India (IN)
- ๐ฆ๐บ Australia (AU)
- ๐ธ๐ฌ Singapore (SG)
- ๐ฐ๐ท South Korea (KR)
- And many more...
South America
- ๐ง๐ท Brazil (BR)
- ๐ฆ๐ท Argentina (AR)
- ๐จ๐ฑ Chile (CL)
- ๐จ๐ด Colombia (CO)
- And more...
Africa & Middle East
- ๐ฟ๐ฆ South Africa (ZA)
- ๐ช๐ฌ Egypt (EG)
- ๐ฎ๐ฑ Israel (IL)
- ๐น๐ท Turkey (TR)
- ๐ธ๐ฆ Saudi Arabia (SA)
- And more...
See the full list of supported countries or use PostcodeChecker.supportedCountries() to get a complete list.
Examples
Validate Multiple Countries
final testCases = {
CountryCode.US: ['12345', '12345-6789', 'INVALID'],
CountryCode.GB: ['SW1A 1AA', 'M1 1AA', '12345'],
CountryCode.DE: ['10115', '80331', '1234'],
CountryCode.JP: ['100-0001', '060-0001', '1000001'],
};
for (final entry in testCases.entries) {
final country = entry.key;
final codes = entry.value;
print('Testing ${country.code}:');
for (final code in codes) {
final result = PostcodeChecker.validate(country, code);
print(' ${code}: ${result.isValid}');
}
}
Custom Validation Function
bool isValidPostalCode(String countryCode, String postalCode) {
// Parse country code string to enum
final country = CountryCode.values.firstWhere(
(c) => c.code == countryCode.toUpperCase(),
orElse: () => throw ArgumentError('Invalid country code: $countryCode'),
);
return PostcodeChecker.validate(country, postalCode).isValid;
}
// Usage
print(isValidPostalCode('US', '12345')); // true
print(isValidPostalCode('GB', 'SW1A 1AA')); // true
API Reference
PostcodeChecker
The main class for validating postal codes.
Methods
-
validate(CountryCode countryCode, String postalCode): Validates a postal code for the specified country. Returns aPostcodeValidationResult. -
getPostalCodePattern(CountryCode countryCode): Returns the regex pattern for the specified country, ornullif not available. -
hasPostalCodes(CountryCode countryCode): Returnstrueif the country has a postal code system. -
supportedCountries(): Returns a list of all countries with postal code validation support.
PostcodeValidationResult
Represents the result of a postal code validation.
Properties
isValid: Whether the postal code is valid.countryCode: The country code used for validation.postalCode: The postal code that was validated.errorMessage: Optional error message if validation failed.
Factory Methods
PostcodeValidationResult.valid(CountryCode, String): Creates a successful validation result.PostcodeValidationResult.invalid(CountryCode, String, String): Creates a failed validation result.
CountryCode
Enum representing ISO 3166-1 alpha-2 country codes.
Extension Methods
code: Returns the two-letter country code as a string.
Data Source
The postal code validation patterns in this package are based on the Unicode CLDR (Common Locale Data Repository) version 26.0.1, which was the last version to include postal code data before it was deprecated in 2016.
CLDR was chosen as the primary data source because:
- โ Maintained by the Unicode Consortium
- โ Widely used and tested
- โ Comprehensive coverage of 170+ territories
- โ Well-documented regex patterns
For countries not covered by CLDR, patterns may be sourced from other reliable sources such as government postal services or international standards organizations.
Pattern Format
All postal code patterns support:
- Optional spacing: Many patterns allow optional spaces (e.g.,
SW1A 1AAorSW1A1AA) - Optional separators: Hyphens and spaces where commonly used (e.g.,
12345-6789) - Case insensitivity: Patterns work with both uppercase and lowercase letters
- Strict validation: Only validates the format, not whether the code actually exists
Contributing
Contributions are welcome! If you find a bug or want to add support for additional countries, please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes with tests
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Adding a New Country Pattern
To add support for a new country:
- Add the pattern to the switch statement in
lib/src/postcode_checker.dart - Add comprehensive tests in
test/postcode_checker_test.dart - Update the documentation
Testing
Run the test suite:
dart test
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- Unicode CLDR: For providing comprehensive postal code patterns
- ISO 3166: For the international standard of country codes
- All contributors who help improve this package
Support
If you find this package helpful, please:
- โญ Star the repository on GitHub
- ๐ Report issues on the issue tracker
- ๐ Contribute improvements via pull requests
Versioning
This package follows Semantic Versioning:
- MAJOR version for incompatible API changes
- MINOR version for backwards-compatible functionality additions
- PATCH version for backwards-compatible bug fixes
Current version: 1.0.2
Made with โค๏ธ by the postcode_checker team
Libraries
- postcode_checker
- A comprehensive Dart package for validating postal codes from countries worldwide using ISO 3166-1 alpha-2 country codes.