0
# Country and Regional Validation
1
2
Validators for country-specific codes, currencies, and regional identifiers. These validators support international standards like ISO 3166 for country codes and ISO 4217 for currency codes.
3
4
## Capabilities
5
6
### Country Code Validation
7
8
Validates country codes according to ISO 3166 standards in multiple formats.
9
10
```python { .api }
11
def country_code(value: str, /, *, iso_format: str = "auto", ignore_case: bool = False) -> Union[Literal[True], ValidationError]:
12
"""
13
Validate ISO 3166 country codes.
14
15
Parameters:
16
- value: Country code string to validate
17
- iso_format: Format to validate ("auto", "alpha2", "alpha3", "numeric")
18
- ignore_case: Whether to ignore case sensitivity
19
20
Returns:
21
True if valid country code, ValidationError otherwise
22
23
Supported formats:
24
- Alpha-2: 2-letter codes (US, GB, FR)
25
- Alpha-3: 3-letter codes (USA, GBR, FRA)
26
- Numeric: 3-digit codes (840, 826, 250)
27
- Auto: Automatically detect format based on input
28
29
Examples:
30
- "US" (Alpha-2), "USA" (Alpha-3), "840" (Numeric) all represent United States
31
"""
32
```
33
34
### Calling Code Validation
35
36
Validates international country calling codes for telephone numbers.
37
38
```python { .api }
39
def calling_code(value: str, /) -> Union[Literal[True], ValidationError]:
40
"""
41
Validate country calling codes (phone number prefixes).
42
43
Parameters:
44
- value: Calling code string to validate (with or without + prefix)
45
46
Returns:
47
True if valid calling code, ValidationError otherwise
48
49
Validates international calling codes:
50
- Format: 1-4 digits, optionally prefixed with '+'
51
- Examples: +1 (US/Canada), +44 (UK), +33 (France), +86 (China)
52
- Supports codes from 1 to 9999
53
54
Accepts both "+1" and "1" formats.
55
"""
56
```
57
58
### Currency Code Validation
59
60
Validates currency codes according to ISO 4217 standard.
61
62
```python { .api }
63
def currency(value: str, /, *, skip_symbols: bool = True, ignore_case: bool = False) -> Union[Literal[True], ValidationError]:
64
"""
65
Validate ISO 4217 currency codes and symbols.
66
67
Parameters:
68
- value: Currency code or symbol to validate
69
- skip_symbols: Skip validation of currency symbols (default True)
70
- ignore_case: Whether to ignore case sensitivity
71
72
Returns:
73
True if valid currency code/symbol, ValidationError otherwise
74
75
Validates:
76
- ISO 4217 3-letter currency codes (USD, EUR, GBP, JPY, etc.)
77
- Currency symbols when skip_symbols=False ($, €, £, ¥, etc.)
78
79
Examples:
80
- Currency codes: "USD", "EUR", "GBP", "JPY", "CNY"
81
- Currency symbols: "$", "€", "£", "¥", "₹" (when enabled)
82
"""
83
```
84
85
## Usage Examples
86
87
```python
88
import validators
89
90
# Country code validation - Auto detection
91
validators.country_code('US') # True (Alpha-2)
92
validators.country_code('USA') # True (Alpha-3)
93
validators.country_code('840') # True (Numeric)
94
95
# Specific format validation
96
validators.country_code('US', iso_format='alpha2') # True
97
validators.country_code('USA', iso_format='alpha3') # True
98
validators.country_code('840', iso_format='numeric') # True
99
100
# Case sensitivity
101
validators.country_code('us') # ValidationError (lowercase)
102
validators.country_code('us', ignore_case=True) # True
103
104
# Invalid country codes
105
validators.country_code('XX') # ValidationError
106
validators.country_code('INVALID') # ValidationError
107
validators.country_code('999') # ValidationError
108
109
# Calling code validation
110
validators.calling_code('+1') # True (US/Canada)
111
validators.calling_code('1') # True (without +)
112
validators.calling_code('+44') # True (UK)
113
validators.calling_code('+33') # True (France)
114
validators.calling_code('+86') # True (China)
115
validators.calling_code('+91') # True (India)
116
117
# Invalid calling codes
118
validators.calling_code('0') # ValidationError
119
validators.calling_code('+0') # ValidationError
120
validators.calling_code('99999') # ValidationError (too long)
121
122
# Currency code validation
123
validators.currency('USD') # True
124
validators.currency('EUR') # True
125
validators.currency('GBP') # True
126
validators.currency('JPY') # True
127
validators.currency('CNY') # True
128
129
# Case sensitivity for currencies
130
validators.currency('usd') # ValidationError (lowercase)
131
validators.currency('usd', ignore_case=True) # True
132
133
# Currency symbols (when enabled)
134
validators.currency('$', skip_symbols=False) # True
135
validators.currency('€', skip_symbols=False) # True
136
validators.currency('£', skip_symbols=False) # True
137
138
# Invalid currencies
139
validators.currency('XXX') # ValidationError
140
validators.currency('INVALID') # ValidationError
141
```
142
143
## Advanced Usage
144
145
### Regional Validation Helper
146
147
```python
148
import validators
149
150
def validate_regional_data(country: str, phone_code: str, currency_code: str) -> dict:
151
"""Validate regional data consistency."""
152
153
results = {
154
'country': bool(validators.country_code(country)),
155
'calling_code': bool(validators.calling_code(phone_code)),
156
'currency': bool(validators.currency(currency_code))
157
}
158
159
# Check for common regional consistency
160
consistency_checks = {
161
('US', '+1', 'USD'): True,
162
('GB', '+44', 'GBP'): True,
163
('FR', '+33', 'EUR'): True,
164
('DE', '+49', 'EUR'): True,
165
('JP', '+81', 'JPY'): True,
166
('CN', '+86', 'CNY'): True,
167
}
168
169
results['consistent'] = (country, phone_code, currency_code) in consistency_checks
170
results['all_valid'] = all(results[k] for k in ['country', 'calling_code', 'currency'])
171
172
return results
173
174
# Usage
175
result = validate_regional_data('US', '+1', 'USD')
176
print(f"Valid: {result['all_valid']}, Consistent: {result['consistent']}")
177
```
178
179
### Country Code Format Conversion
180
181
```python
182
import validators
183
184
# Mapping between country code formats (partial example)
185
COUNTRY_MAPPINGS = {
186
'US': {'alpha3': 'USA', 'numeric': '840', 'name': 'United States'},
187
'GB': {'alpha3': 'GBR', 'numeric': '826', 'name': 'United Kingdom'},
188
'FR': {'alpha3': 'FRA', 'numeric': '250', 'name': 'France'},
189
'DE': {'alpha3': 'DEU', 'numeric': '276', 'name': 'Germany'},
190
'JP': {'alpha3': 'JPN', 'numeric': '392', 'name': 'Japan'},
191
}
192
193
def convert_country_code(code: str, target_format: str) -> str:
194
"""Convert between country code formats."""
195
196
# First validate the input code
197
if not validators.country_code(code):
198
raise ValueError(f"Invalid country code: {code}")
199
200
# Determine input format
201
if len(code) == 2 and code.isalpha():
202
source_format = 'alpha2'
203
lookup_key = code.upper()
204
elif len(code) == 3 and code.isalpha():
205
source_format = 'alpha3'
206
# Find alpha2 key by alpha3 value
207
lookup_key = None
208
for k, v in COUNTRY_MAPPINGS.items():
209
if v['alpha3'] == code.upper():
210
lookup_key = k
211
break
212
elif len(code) == 3 and code.isdigit():
213
source_format = 'numeric'
214
# Find alpha2 key by numeric value
215
lookup_key = None
216
for k, v in COUNTRY_MAPPINGS.items():
217
if v['numeric'] == code:
218
lookup_key = k
219
break
220
else:
221
raise ValueError(f"Cannot determine format for: {code}")
222
223
if not lookup_key or lookup_key not in COUNTRY_MAPPINGS:
224
raise ValueError(f"Country code not found in mapping: {code}")
225
226
if target_format == 'alpha2':
227
return lookup_key
228
elif target_format == 'alpha3':
229
return COUNTRY_MAPPINGS[lookup_key]['alpha3']
230
elif target_format == 'numeric':
231
return COUNTRY_MAPPINGS[lookup_key]['numeric']
232
else:
233
raise ValueError(f"Invalid target format: {target_format}")
234
235
# Usage examples
236
print(convert_country_code('US', 'alpha3')) # USA
237
print(convert_country_code('USA', 'alpha2')) # US
238
print(convert_country_code('840', 'alpha2')) # US
239
```
240
241
## Common Country/Region Combinations
242
243
### Major Economies
244
245
```python
246
import validators
247
248
# Validate major world economies
249
major_economies = [
250
('US', '+1', 'USD'), # United States
251
('CN', '+86', 'CNY'), # China
252
('JP', '+81', 'JPY'), # Japan
253
('DE', '+49', 'EUR'), # Germany
254
('GB', '+44', 'GBP'), # United Kingdom
255
('FR', '+33', 'EUR'), # France
256
('IN', '+91', 'INR'), # India
257
('IT', '+39', 'EUR'), # Italy
258
('BR', '+55', 'BRL'), # Brazil
259
('CA', '+1', 'CAD'), # Canada
260
]
261
262
for country, phone, currency in major_economies:
263
valid_country = validators.country_code(country)
264
valid_phone = validators.calling_code(phone)
265
valid_currency = validators.currency(currency)
266
267
print(f"{country}: Country={valid_country}, Phone={valid_phone}, Currency={valid_currency}")
268
```
269
270
### European Union Countries
271
272
```python
273
import validators
274
275
# EU countries using EUR currency
276
eu_euro_countries = [
277
('DE', '+49'), # Germany
278
('FR', '+33'), # France
279
('IT', '+39'), # Italy
280
('ES', '+34'), # Spain
281
('NL', '+31'), # Netherlands
282
('BE', '+32'), # Belgium
283
('AT', '+43'), # Austria
284
('PT', '+351'), # Portugal
285
('IE', '+353'), # Ireland
286
('FI', '+358'), # Finland
287
]
288
289
for country, phone in eu_euro_countries:
290
all_valid = (
291
validators.country_code(country) and
292
validators.calling_code(phone) and
293
validators.currency('EUR')
294
)
295
print(f"{country} + EUR: {all_valid}")
296
```