When storing phone numbers in the backend, it’s crucial to consider efficiency, standardization, validation, and internationalization. The best way to store phone numbers often depends on your application’s needs (e.g., international support, validation rules, format requirements).
This approach stores the full phone number, including the country code, in international E.164 format (which is the internationally recognized phone number format).
Consistency: By storing phone numbers in E.164 format, you avoid inconsistencies in formatting across different users and systems.
Validation: You can easily validate phone numbers using libraries such as libphonenumber (used by Google) to verify that the phone number is well-formed and valid for a specific country.
Database Schema: Store the phone number as a single string field in E.164 format.
Field type: String or VARCHAR (depending on the database).
Example: VARCHAR(15) (E.164 allows a maximum of 15 digits).
CREATE TABLE users ( id INT PRIMARY KEY, phone_number VARCHAR(15) NOT NULL );
In this approach, you split the phone number into two fields: one for the country code and one for the local number. This allows more flexibility for localized formatting and may be preferable if your application requires different phone number behaviors by region (e.g., validation rules, format display).
CREATE TABLE users ( id INT PRIMARY KEY, phone_number VARCHAR(15) NOT NULL );
Here’s a full example of handling phone numbers with E.164 format and libphonenumber for validation in Node.js:
CREATE TABLE users ( id INT PRIMARY KEY, country_code VARCHAR(5) NOT NULL, local_number VARCHAR(20) NOT NULL );
npm install google-libphonenumber
To retrieve the country code (like US for United States) from a phone number using this library, you can use the getRegionCodeForNumber function. This function takes a phone number (which must be parsed using parseAndKeepRawInput or similar) and returns the country code in the ISO 3166-1 alpha-2 format (e.g., IN, US, GB, etc.).
const { PhoneNumberUtil, PhoneNumberFormat } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const validatePhoneNumber = (phoneNumber, countryCode) => { try { const number = phoneUtil.parseAndKeepRawInput(phoneNumber, countryCode); const isValid = phoneUtil.isValidNumber(number); const formattedNumber = phoneUtil.format(number, PhoneNumberFormat.E164); return { isValid, formattedNumber }; } catch (error) { return { isValid: false, error: 'Invalid phone number' }; } }; // Example usage const { isValid, formattedNumber } = validatePhoneNumber('800-555-5555', 'US'); console.log(isValid, formattedNumber); // true, +18005555555
parseAndKeepRawInput(phoneNumber):
This method is used to parse the phone number and keep the raw input, meaning it can handle input in various formats (e.g., with spaces, dashes, or parentheses).
getRegionCodeForNumber(number):
This function returns the country code (ISO 3166-1 alpha-2 code, such as IN, US, GB, etc.) associated with the parsed phone number.
It does this by matching the number against its internal list of country-specific phone number patterns.
const { PhoneNumberUtil } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); // Function to get country code (ISO 3166-1 alpha-2) const getCountryCodeFromPhoneNumber = (phoneNumber) => { try { // Parse the phone number and get the region (country code) const number = phoneUtil.parseAndKeepRawInput(phoneNumber); const countryCode = phoneUtil.getRegionCodeForNumber(number); return countryCode; } catch (error) { console.error("Error parsing phone number:", error); return null; } }; // Test with different phone numbers const testPhoneNumbers = [ "+919167988354", // India "+14155552671", // USA "+447777123456", // UK "+81 90 1234 5678", // Japan ]; testPhoneNumbers.forEach((phoneNumber) => { const countryCode = getCountryCodeFromPhoneNumber(phoneNumber); console.log(`Phone number: ${phoneNumber}, Country Code: ${countryCode}`); });
The phone number must be parsed correctly, and it should include the country code ( followed by digits). If the phone number is in local format (without the country code), you will need to specify the default region (country) while parsing.
Default region: If the phone number doesn't contain a country code, you can provide a default country code using the parse method (e.g., phoneUtil.parse(phoneNumber, 'IN') for India).
The above is the detailed content of Best way to store phone numbers in your app. For more information, please follow other related articles on the PHP Chinese website!