global-form-intelligence
v1.0.1
Published
A complete SDK for handling global form validation, formatting, and metadata including countries, phone numbers, addresses, and currencies.
Downloads
22
Maintainers
Readme
Global Form Intelligence
A complete, production-ready SDK for handling global form validation, formatting, and metadata. It provides a comprehensive toolkit for developers building applications with international user bases.
This package offers utilities for countries, phone numbers, addresses, currencies, states, and cities, all accessible through a simple and powerful API.
Features
- 🌍 Country Metadata: Access a wealth of data for all countries, including ISO codes, names, phone codes, currency info, flags, and more.
- 📱 Phone Handling: Validate, format, and detect countries from phone numbers using the power of
libphonenumber-js. - 📫 Address Validation: Perform country-specific postal/ZIP code validation.
- 💰 Currency Utilities: Format currency values according to locale and access currency symbols.
- 🗺️ States & Cities: Efficiently look up states/provinces for any country and major cities for any state.
- ⚙️ Form Validator Engine: A single, powerful function to validate an entire form's data (
phone,postalCode,state, etc.) based on the selected country. - 🇹🇸 TypeScript Ready: Fully written in TypeScript with comprehensive type definitions.
- 🌳 Tree-shakeable: Import only the functions you need to keep your bundle size small.
Installation
npm install global-form-intelligenceUsage Examples
Here are real-world examples demonstrating the library's capabilities.
Example 1: Get All Countries
Fetch a complete list of countries with all associated metadata.
import { getAllCountries } from 'global-form-intelligence';
const countries = getAllCountries();
console.log(`Total countries loaded: ${countries.length}`);
console.log('Sample (USA):', countries.find(c => c.isoCode === 'US'));Expected Output:
{
"name": "United States",
"isoCode": "US",
"iso3": "USA",
"phonecode": "+1",
"currency": "USD",
"flag": "🇺🇸",
"postalCodeSupport": true,
"flagUrl": "https://flagcdn.com/w320/us.png",
"locales": ["en-US"]
}Example 2: Get Specific Country Info
Look up a country by its ISO2 (e.g., 'DE') or ISO3 (e.g., 'DEU') code.
import { getCountryByCode } from 'global-form-intelligence';
const germany = getCountryByCode('DE');
console.log('Germany Info:', germany);Expected Output:
{
"name": "Germany",
"isoCode": "DE",
"iso3": "DEU",
"phonecode": "+49",
"currency": "EUR",
"flag": "🇩🇪",
"postalCodeSupport": true,
"flagUrl": "https://flagcdn.com/w320/de.png",
"locales": ["de-DE"]
}Example 3: Phone Validation
Check if a phone number is valid for a specific country.
import { validatePhone } from 'global-form-intelligence';
const isValidUS = validatePhone('202-555-0104', 'US');
const isInvalidDE = validatePhone('12345', 'DE');
console.log('Is US number valid?', isValidUS); // true
console.log('Is German number valid?', isInvalidDE); // falseExample 4: Phone Formatting
Format a phone number into national and international standards.
import { formatPhone } from 'global-form-intelligence';
const formattedGB = formatPhone('07911 123456', 'GB');
console.log('UK Phone:', formattedGB);Expected Output:
{
"national": "07911 123456",
"international": "+44 7911 123456"
}Example 5: Detect Country from Phone
Identify the country from a phone number in international format.
import { detectCountryFromPhone } from 'global-form-intelligence';
const countryCode = detectCountryFromPhone('+91 98765 43210');
console.log('Detected Country Code:', countryCode); // 'IN'Example 6: Postal Code Validation
Validate a postal code against country-specific rules.
import { validatePostalCode } from 'global-form-intelligence';
const validCAPostalCode = validatePostalCode('M5V 2T6', 'CA'); // Toronto
const invalidUSZipCode = validatePostalCode('1234', 'US');
console.log('Is Canadian postal code valid?', validCAPostalCode); // true
console.log('Is US ZIP code valid?', invalidUSZipCode); // falseExample 7: Currency Formatting
Display a numeric amount as a locale-aware currency string.
import { formatCurrency } from 'global-form-intelligence';
const amountInYen = formatCurrency(150000, 'JPY');
const amountInEuros = formatCurrency(199.99, 'EUR', 'de-DE');
console.log(amountInYen); // ¥150,000
console.log(amountInEuros); // 199,99 €Example 8: Get States & Cities
List all states for a country and all major cities for a state.
import { getStates, getCities } from 'global-form-intelligence';
const australianStates = getStates('AU');
const nsw = australianStates.find(s => s.isoCode === 'NSW');
console.log('New South Wales:', nsw);
if (nsw) {
const nswCities = getCities('AU', nsw.isoCode);
console.log('Major city in NSW:', nswCities.find(c => c.name === 'Sydney'));
}Example 9: Full Form Validation (The Powerhouse)
Use the validateForm engine to check multiple fields at once.
import { validateForm } from 'global-form-intelligence';
const validSubmission = {
country: 'US',
phone: '(415) 555-2671',
postalCode: '94107',
state: 'CA',
city: 'San Francisco'
};
const invalidSubmission = {
country: 'GB',
phone: '555-0199', // Invalid for GB
postalCode: '12345', // Invalid for GB
};
const result1 = validateForm(validSubmission);
console.log('Valid Submission:', result1);
const result2 = validateForm(invalidSubmission);
console.log('Invalid Submission:', result2);Expected Output:
{
"valid": true,
"errors": {}
}
{
"valid": false,
"errors": {
"phone": "Invalid phone number for the selected country.",
"postalCode": "Invalid postal code for the selected country."
}
}API Reference
| Function | Parameters | Returns | Description |
| ------------------------ | -------------------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------- |
| getAllCountries() | - | Country[] | Returns an array of all country objects. |
| getCountryByCode(code) | code: string (ISO2 or ISO3) | Country \| null | Finds a single country by its code. |
| getStates(countryCode) | countryCode: string | State[] | Gets all states/provinces for a country. |
| getCities(country, state) | countryCode: string, stateCode: string | City[] | Gets major cities for a state. |
| validatePhone(num, cc) | num: string, cc: string | boolean | Validates a phone number against a country. |
| formatPhone(num, cc) | num: string, cc: string | { national, international } \| null | Formats a phone number. |
| detectCountryFromPhone(num) | num: string | string \| null (Country Code) | Detects the country from an international phone number. |
| validatePostalCode(pc, cc) | pc: string, cc: string | boolean | Validates a postal code for a country. |
| formatCurrency(amt, cur, loc?) | amt: number, cur: string, loc?: string | string | Formats a number into a currency string. |
| getCurrencySymbol(cur) | cur: string | string \| undefined | Gets the symbol for a currency code (e.g., 'USD' -> '$'). |
| getFlag(countryCode) | countryCode: string | Flag \| null | Gets flag emoji and CDN URL for a country. |
| validateForm(input) | input: FormValidationInput | FormValidationResult | The main engine to validate a set of form fields. |
TypeScript Support
This library is built with TypeScript and exports all its types.
import { validateForm, FormValidationInput, FormValidationResult } from 'global-form-intelligence';
const myForm: FormValidationInput = {
country: 'FR',
phone: '0612345678',
postalCode: '75001'
};
const result: FormValidationResult = validateForm(myForm);
if (!result.valid) {
console.error(result.errors);
}Tree-shaking
The library is designed to be tree-shakeable. If you only need a specific function, you can import it directly to reduce your final bundle size.
// This will only include the validatePostalCode function and its
// minimal dependencies in your final application bundle.
import { validatePostalCode } from 'global-form-intelligence';
console.log(validatePostalCode('SW1A 0AA', 'GB')); // trueContributing
Contributions, issues, and feature requests are welcome! Feel free to check the issues page. If you find any issue or bug, please reach out to [email protected].
License
This project is MIT licensed.
