### Install google-libphonenumber Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Install the package using npm. This command adds the library as a production dependency. ```sh npm install --save-prod google-libphonenumber ``` -------------------------------- ### Get ShortNumberInfo Instance Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Obtain an instance of ShortNumberInfo to work with short number information. This is a prerequisite for using its methods. ```javascript const shortInfo = require('google-libphonenumber').ShortNumberInfo.getInstance(); ``` -------------------------------- ### Extract Phone Number Information Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md This example shows how to parse a raw phone number string, extract various components like country code, national number, and extension, and then validate and format the number. ```javascript // Require `PhoneNumberFormat`. const PNF = require('google-libphonenumber').PhoneNumberFormat; // Get an instance of `PhoneNumberUtil`. const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance(); // Parse number with country code and keep raw input. const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US'); // Print the phone's country code. console.log(number.getCountryCode()); // => 1 // Print the phone's national number. console.log(number.getNationalNumber()); // => 2024561414 // Print the phone's extension. console.log(number.getExtension()); // => // Print the phone's extension when compared to i18n.phonenumbers.CountryCodeSource. console.log(number.getCountryCodeSource()); // => FROM_DEFAULT_COUNTRY // Print the phone's italian leading zero. console.log(number.getItalianLeadingZero()); // => false // Print the phone's raw input. console.log(number.getRawInput()); // => 202-456-1414 // Result from isPossibleNumber(). console.log(phoneUtil.isPossibleNumber(number)); // => true // Result from isValidNumber(). console.log(phoneUtil.isValidNumber(number)); // => true // Result from isValidNumberForRegion(). console.log(phoneUtil.isValidNumberForRegion(number, 'US')); // => true // Result from getRegionCodeForNumber(). console.log(phoneUtil.getRegionCodeForNumber(number)); // => US // Result from getNumberType() when compared to i18n.phonenumbers.PhoneNumberType. console.log(phoneUtil.getNumberType(number)); // => FIXED_LINE_OR_MOBILE // Format number in the E164 format. console.log(phoneUtil.format(number, PNF.E164)); // => +12024561414 // Format number in the original format. console.log(phoneUtil.formatInOriginalFormat(number, 'US')); // => (202) 456-1414 // Format number in the national format. console.log(phoneUtil.format(number, PNF.NATIONAL)); // => (202) 456-1414 // Format number in the international format. console.log(phoneUtil.format(number, PNF.INTERNATIONAL)); // => +1 202-456-1414 // Format number in the out-of-country format from US. console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'US')); // => 1 (202) 456-1414 // Format number in the out-of-country format from CH. console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'CH')); // => 00 1 202-456-1414 ``` -------------------------------- ### Get PhoneNumberUtil Instance Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Obtain an instance of PhoneNumberUtil, which is necessary for parsing phone numbers before using them with ShortNumberInfo methods. ```javascript const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance(); ``` -------------------------------- ### Validate Phone Number Possibility with ValidationResult Enum Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Illustrates using `isPossibleNumberWithReason` to get specific reasons for phone number validation failures. Handles potential parsing errors for invalid formats. ```javascript const { PhoneNumberUtil } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const ValidationResult = PhoneNumberUtil.ValidationResult; const cases = [ { raw: '123456', region: 'US', expected: 'TOO_SHORT' }, { raw: '12345678901234567890', region: 'US', expected: 'TOO_LONG (parse throws)' }, { raw: '2024561414', region: 'US', expected: 'IS_POSSIBLE' }, ]; cases.forEach(({ raw, region }) => { try { const number = phoneUtil.parse(raw, region); const result = phoneUtil.isPossibleNumberWithReason(number); // result === ValidationResult.IS_POSSIBLE (0) // result === ValidationResult.TOO_SHORT (2) // result === ValidationResult.TOO_LONG (3) // result === ValidationResult.INVALID_COUNTRY_CODE (1) console.log(`${raw}: ${result}`); } catch (e) { console.error(`${raw}: threw — ${e.message}`); } }); // => 123456: 2 (TOO_SHORT) // => 2024561414: 0 (IS_POSSIBLE) ``` -------------------------------- ### Determine the reason for a phone number's invalidity Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Use isPossibleNumberWithReason to get a ValidationResult enum indicating why a number is considered invalid, such as being too short. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const shortNumber = phoneUtil.parseAndKeepRawInput('123456', 'US'); console.log(phoneUtil.isPossibleNumber(shortNumber)); // => false console.log(phoneUtil.isPossibleNumberWithReason(shortNumber)); // => PhoneNumberUtil.ValidationResult.TOO_SHORT ``` -------------------------------- ### Run Tests with npm Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Execute the library's test suite using the npm test command. ```sh npm test ``` -------------------------------- ### Using AsYouTypeFormatter for Real-time Formatting Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Instantiate AsYouTypeFormatter with a region code and input digits one by one to see formatting progress. Call clear() to reset the formatter. ```javascript const AsYouTypeFormatter = require('google-libphonenumber').AsYouTypeFormatter; const formatter = new AsYouTypeFormatter('US'); console.log(formatter.inputDigit('2')); // => 2 console.log(formatter.inputDigit('0')); // => 20 console.log(formatter.inputDigit('2')); // => 202 console.log(formatter.inputDigit('-')); // => 202- console.log(formatter.inputDigit('4')); // => 202-4 console.log(formatter.inputDigit('5')); // => 202-45 console.log(formatter.inputDigit('6')); // => 202-456 console.log(formatter.inputDigit('-')); // => 202-456- console.log(formatter.inputDigit('1')); // => 202-456-1 console.log(formatter.inputDigit('4')); // => 202-456-14 console.log(formatter.inputDigit('1')); // => 202-456-141 console.log(formatter.inputDigit('4')); // => 202-456-1414 // Cleanup all input digits from instance. formatter.clear(); ``` -------------------------------- ### Import and inspect all exports from google-libphonenumber Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Import the library and log all available top-level exports to the console. This helps in understanding the full API surface. ```js const libphonenumber = require('google-libphonenumber'); // Available exports (sorted): // AsYouTypeFormatter // Error // NumberFormat // PhoneMetadata // PhoneMetadataCollection // PhoneNumber // PhoneNumberDesc // PhoneNumberFormat // PhoneNumberType // PhoneNumberUtil // ShortNumberInfo // metadata // shortnumbermetadata console.log(Object.keys(libphonenumber).sort()); // => ['AsYouTypeFormatter', 'Error', 'NumberFormat', 'PhoneMetadata', // 'PhoneMetadataCollection', 'PhoneNumber', 'PhoneNumberDesc', // 'PhoneNumberFormat', 'PhoneNumberType', 'PhoneNumberUtil', // 'ShortNumberInfo', 'metadata', 'shortnumbermetadata'] ``` -------------------------------- ### Real-time Formatting with AsYouTypeFormatter (International) Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Demonstrates formatting international numbers with a leading plus sign using `AsYouTypeFormatter`. Initialize with 'ZZ' for an unknown region and input digits. ```javascript const { AsYouTypeFormatter } = require('google-libphonenumber'); // International number typed with leading + const intFormatter = new AsYouTypeFormatter('ZZ'); // ZZ = unknown region '+12024561414'.split('').forEach(digit => { process.stdout.write(intFormatter.inputDigit(digit) + '\n'); }); // => + // => +1 // => +1 2 // => +1 20 // => +1 202 // => +1 202-4 // => +1 202-45 // => +1 202-456 // => +1 202-456-1 // => +1 202-456-14 // => +1 202-456-141 // => +1 202-456-1414 ``` -------------------------------- ### Real-time Formatting with AsYouTypeFormatter (Portuguese) Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Shows incremental formatting for Portuguese phone numbers. Use `AsYouTypeFormatter` instantiated with 'PT' and feed digits sequentially. ```javascript const { AsYouTypeFormatter } = require('google-libphonenumber'); // Portuguese number: 912 345 678 const ptFormatter = new AsYouTypeFormatter('PT'); '912345678'.split('').forEach(digit => { process.stdout.write(ptFormatter.inputDigit(digit) + '\n'); }); // => 9 // => 91 // => 912 // => 912 3 // => 912 34 // => 912 345 // => 912 345 6 // => 912 345 67 // => 912 345 678 ``` -------------------------------- ### Update seegno-closure-library in package.json Source: https://github.com/ruimarinho/google-libphonenumber/wiki/Updating-Package-Dependencies Specifies a direct git dependency for seegno-closure-library in your project's package.json file. Replace ``, `` with your fork details and desired reference. ```json "dependencies": { "seegno-closure-library": "git://github.com//closure-library#" } ``` -------------------------------- ### Format a phone number for dialing from another country Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Shows how to format a phone number for international dialing from a specified country, considering different dialing prefixes. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('202-456-1414', 'US'); // formatOutOfCountryCallingNumber — how to dial from another country console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'US')); // => '1 (202) 456-1414' console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'CH')); // => '00 1 202-456-1414' ``` -------------------------------- ### Version Release with npm Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Use the npm version command to manage package releases, specifying a new version or using keywords like major, minor, or patch. Includes a commit message format. ```sh npm version [ | major | minor | patch] -m "Release %s" ``` -------------------------------- ### Real-time Formatting with AsYouTypeFormatter (US) Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Demonstrates incremental phone number formatting for US numbers as digits are typed. Instantiate with 'US' and call `inputDigit` for each character. ```javascript const { AsYouTypeFormatter } = require('google-libphonenumber'); // US number: (202) 456-1414 const usFormatter = new AsYouTypeFormatter('US'); '2024561414'.split('').forEach(digit => { process.stdout.write(usFormatter.inputDigit(digit) + '\n'); }); // => 2 // => 20 // => 202 // => 202-4 // => 202-45 // => 202-456 // => 202-456-1 // => 202-456-14 // => 202-456-141 // => (202) 456-1414 usFormatter.clear(); // reset for reuse ``` -------------------------------- ### Initialize PhoneNumberUtil and parse a phone number Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Obtain the PhoneNumberUtil instance and parse a phone number string with a default region. This method throws an error on invalid input. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); // --- Parsing --- // parse(numberString, defaultRegion) — throws on invalid input const number = phoneUtil.parse('202-456-1414', 'US'); ``` -------------------------------- ### Make Depswriter Executable Source: https://github.com/ruimarinho/google-libphonenumber/wiki/Updating-Package-Dependencies Grants execute permissions to the depswriter.py script, which is necessary for regenerating dependency files. ```sh chmod +x node_modules/seegno-closure-library/closure/bin/build/depswriter.py ``` -------------------------------- ### Regenerate Closure Library Dependencies Source: https://github.com/ruimarinho/google-libphonenumber/wiki/Updating-Package-Dependencies Removes the existing deps.js file and then uses the depswriter.py script to generate a new one, filtering out specific metadata files and adjusting pathing. This command should be run after updating libphonenumber if its dependencies have changed. ```sh rm ./lib/closure/goog/deps.js && node_modules/seegno-closure-library/closure/bin/build/depswriter.py --root_with_prefix="./lib/closure/goog" '/lib/closure/goog' | sed -E '/metadatalite|metadatafortesting/d' | sed -E $'s/\'/basePath + \'/' > ./lib/closure/goog/deps.js ``` -------------------------------- ### Fetch libphonenumber Update Source: https://github.com/ruimarinho/google-libphonenumber/wiki/Updating-Package-Dependencies Fetches a specific tag or revision of libphonenumber from its GitHub repository and extracts the JavaScript files to the correct directory. Ensure you replace `` with the desired version. ```sh curl -L https://github.com/googlei18n/libphonenumber/archive/libphonenumber-.tar.gz | tar -xvf - --strip-components=4 -C lib/closure/goog/i18n/phonenumbers --include=*javascript/i18n/phonenumbers* ``` -------------------------------- ### ShortNumberInfo Methods Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Provides methods to interact with short phone number information. ```APIDOC ## ShortNumberInfo ### Description Provides methods to test and validate short phone numbers. ### Methods - **connectsToEmergencyNumber(number, regionCode)** - Description: Tests whether the short number can be used to connect to emergency services when dialed from the given region. - Parameters: - number (string): The short number to test. - regionCode (string): The region code (e.g., 'US'). - Returns: boolean - **isPossibleShortNumber(number)** - Description: Tests whether a short number is a possible number. - Parameters: - number (object): A PhoneNumber object. - Returns: boolean - **isPossibleShortNumberForRegion(number, regionDialingFrom)** - Description: Tests whether a short number is a possible number when dialed from the given region. - Parameters: - number (object): A PhoneNumber object. - regionDialingFrom (string): The region code from which the number is dialed. - Returns: boolean - **isValidShortNumber(number)** - Description: Tests whether a short number is a possible number. - Parameters: - number (object): A PhoneNumber object. - Returns: boolean - **isValidShortNumberForRegion(number, regionDialingFrom)** - Description: Tests whether a short number matches a valid pattern in a region. - Parameters: - number (object): A PhoneNumber object. - regionDialingFrom (string): The region code. - Returns: boolean ### Usage Examples ```js // Get an instance of `ShortNumberInfo`. const shortInfo = require('google-libphonenumber').ShortNumberInfo.getInstance(); // Get an instance of `PhoneNumberUtil`. const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance(); // Result from connectsToEmergencyNumber(). console.log(shortInfo.connectsToEmergencyNumber('911', 'US')); // => true // Result from isPossibleShortNumber(). console.log(shortInfo.isPossibleShortNumber(phoneUtil.parse('123456', 'FR'))); // => true // Result from isPossibleShortNumberForRegion(). console.log(shortInfo.isPossibleShortNumberForRegion(phoneUtil.parse('123456', 'FR'), 'FR')); // => true ``` ``` -------------------------------- ### Test AsYouTypeFormatter with UK Numbers Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/src/asyoutypeformatter_test.html Tests the formatting of UK phone numbers as they are typed. Verifies correct formatting for international dialing codes and local numbers. ```javascript var formatter = new i18n.phonenumbers.AsYouTypeFormatter('GB'); assertEquals('+44', formatter.inputDigit('+')); assertEquals('+44 1', formatter.inputDigit('1')); assertEquals('+44 12', formatter.inputDigit('2')); assertEquals('+44 123', formatter.inputDigit('3')); assertEquals('+44 1233', formatter.inputDigit('3')); assertEquals('+44 1233 4', formatter.inputDigit('4')); assertEquals('+44 1233 45', formatter.inputDigit('5')); assertEquals('+44 1233 456', formatter.inputDigit('6')); assertEquals('+44 1233 4567', formatter.inputDigit('7')); assertEquals('+44 1233 45678', formatter.inputDigit('8')); assertEquals('+44 1233 456789', formatter.inputDigit('9')); ``` -------------------------------- ### ShortNumberInfo Utility Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt The ShortNumberInfo singleton provides methods to validate and classify short phone codes, such as emergency numbers and SMS short codes. Obtain an instance using ShortNumberInfo.getInstance(). ```APIDOC ## ShortNumberInfo — Short Code & Emergency Number Utility `ShortNumberInfo` is a singleton for validating and classifying short phone codes (e.g., emergency numbers, SMS short codes). Obtain via `ShortNumberInfo.getInstance()`. ### Methods - **connectsToEmergencyNumber(numberString, regionCode)**: Checks if a given number string connects to an emergency service in the specified region. - **isPossibleShortNumber(PhoneNumber)**: Determines if a parsed PhoneNumber object represents a possible short number. - **isPossibleShortNumberForRegion(PhoneNumber, regionCode)**: Determines if a parsed PhoneNumber object is a possible short number for a specific region. - **isValidShortNumber(PhoneNumber)**: Validates if a parsed PhoneNumber object is a valid short number. - **isValidShortNumberForRegion(PhoneNumber, regionCode)**: Validates if a parsed PhoneNumber object is a valid short number for a specific region. ### Example Usage ```js const { ShortNumberInfo, PhoneNumberUtil } = require('google-libphonenumber'); const shortInfo = ShortNumberInfo.getInstance(); const phoneUtil = PhoneNumberUtil.getInstance(); // connectsToEmergencyNumber(numberString, regionCode) console.log(shortInfo.connectsToEmergencyNumber('911', 'US')); // => true console.log(shortInfo.connectsToEmergencyNumber('999', 'GB')); // => true console.log(shortInfo.connectsToEmergencyNumber('123', 'US')); // => false // isPossibleShortNumber(PhoneNumber) — takes a parsed PhoneNumber object const fr123 = phoneUtil.parse('123456', 'FR'); console.log(shortInfo.isPossibleShortNumber(fr123)); // => true // isPossibleShortNumberForRegion(PhoneNumber, regionCode) console.log(shortInfo.isPossibleShortNumberForRegion(fr123, 'FR')); // => true console.log(shortInfo.isPossibleShortNumberForRegion(fr123, 'DE')); // => false // isValidShortNumber(PhoneNumber) const usShort = phoneUtil.parse('40404', 'US'); console.log(shortInfo.isValidShortNumber(usShort)); // => true // isValidShortNumberForRegion(PhoneNumber, regionCode) console.log(shortInfo.isValidShortNumberForRegion(usShort, 'US')); // => true console.log(shortInfo.isValidShortNumberForRegion(usShort, 'GB')); // => false ``` ``` -------------------------------- ### Test AsYouTypeFormatter with International Numbers Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/src/asyoutypeformatter_test.html Tests the formatting of various international phone numbers. Covers cases with different country codes and number structures. ```javascript var formatter = new i18n.phonenumbers.AsYouTypeFormatter('ZZ'); assertEquals("020 7123 4567", formatter.inputDigit('0')); assertEquals("+44 20 7123 4567", formatter.inputDigit('4')); assertEquals("+44 20 7123 4567", formatter.inputDigit('4')); ``` -------------------------------- ### Handle errors during phone number parsing Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Demonstrates error handling for malformed phone number input, such as strings that are too long to be valid numbers. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); // --- Error handling for malformed input --- try { phoneUtil.parseAndKeepRawInput('111111111111111111111', 'US'); } catch (e) { console.error(e.message); // => 'The string supplied is too long to be a phone number' } ``` -------------------------------- ### Test AsYouTypeFormatter with US Numbers Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/src/asyoutypeformatter_test.html Tests the formatting of US phone numbers as they are typed. Ensures correct formatting for different stages of input. ```javascript goog.require('goog.proto2.Message'); goog.require('i18n.phonenumbers.AsYouTypeFormatter'); var formatter = new i18n.phonenumbers.AsYouTypeFormatter('US'); assertEquals('1', formatter.inputDigit('1')); assertEquals('12', formatter.inputDigit('2')); assertEquals('123', formatter.inputDigit('3')); assertEquals('1234', formatter.inputDigit('4')); assertEquals('12345', formatter.inputDigit('5')); assertEquals('123456', formatter.inputDigit('6')); assertEquals('1234567', formatter.inputDigit('7')); assertEquals('12345678', formatter.inputDigit('8')); assertEquals('123456789', formatter.inputDigit('9')); assertEquals('1 (234) 567-8901', formatter.inputDigit('0')); ``` -------------------------------- ### PhoneNumberUtil - Core Utility Class Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt The PhoneNumberUtil class is a singleton used for parsing, formatting, validating, and classifying phone numbers. Obtain an instance using PhoneNumberUtil.getInstance(). Methods typically expect a parsed PhoneNumber object. ```APIDOC ## PhoneNumberUtil - Core Utility Class ### Description `PhoneNumberUtil` is a singleton that provides parsing, formatting, validation, and classification of phone numbers. Always obtain it via `PhoneNumberUtil.getInstance()` — never construct it directly. All methods that accept a phone number expect a parsed `PhoneNumber` proto object (not a raw string). ### Methods #### Parsing - **parse(numberString, defaultRegion)**: Parses a phone number string. Throws an error on invalid input. - **parseAndKeepRawInput(numberString, defaultRegion)**: Parses a phone number string and retains the original input string. #### Formatting - **format(number, format)**: Formats a parsed `PhoneNumber` object into a specified format (e.g., E164, INTERNATIONAL, NATIONAL, RFC3966). - **formatInOriginalFormat(number, defaultRegion)**: Formats a parsed `PhoneNumber` object using its original string's formatting style. - **formatOutOfCountryCallingNumber(number, countryCode)**: Formats a phone number for dialing from a different country. #### Validation - **isValidNumber(number)**: Checks if a parsed `PhoneNumber` object represents a valid phone number. - **isValidNumberForRegion(number, regionCode)**: Checks if a parsed `PhoneNumber` object is valid for a specific region. - **isPossibleNumber(number)**: Checks if a parsed `PhoneNumber` object is potentially a valid phone number (less strict than `isValidNumber`). - **isPossibleNumberWithReason(number)**: Returns a `ValidationResult` enum indicating why a number might be considered impossible or invalid (e.g., TOO_SHORT, TOO_LONG). #### Classification - **getNumberType(number)**: Determines the type of a parsed `PhoneNumber` object (e.g., FIXED_LINE_OR_MOBILE, MOBILE, FIXED_LINE). - **getRegionCodeForNumber(number)**: Retrieves the region code associated with a parsed `PhoneNumber` object. ### Example Usage ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); // Parsing const number = phoneUtil.parse('202-456-1414', 'US'); const numberRaw = phoneUtil.parseAndKeepRawInput('+44 20 7183 8750', 'GB'); // Accessing fields console.log(number.getCountryCode()); // => 1 console.log(number.getNationalNumber()); // => 2024561414 console.log(numberRaw.getRawInput()); // => '+44 20 7183 8750' // Formatting console.log(phoneUtil.format(number, PNF.E164)); // => '+12024561414' console.log(phoneUtil.format(number, PNF.INTERNATIONAL)); // => '+1 202-456-1414' // Validation console.log(phoneUtil.isValidNumber(number)); // => true // Classification console.log(phoneUtil.getNumberType(number)); // => FIXED_LINE_OR_MOBILE (PNT) console.log(phoneUtil.getRegionCodeForNumber(number)); // => 'US' // Error Handling try { phoneUtil.parseAndKeepRawInput('111111111111111111111', 'US'); } catch (e) { console.error(e.message); // => 'The string supplied is too long to be a phone number' } ``` ``` -------------------------------- ### Test AsYouTypeFormatter with Reset Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/src/asyoutypeformatter_test.html Tests the reset functionality of the AsYouTypeFormatter. Ensures that the formatter can be reused for a new number after being reset. ```javascript var formatter = new i18n.phonenumbers.AsYouTypeFormatter('US'); assertEquals('1', formatter.inputDigit('1')); formatter.clear(); assertEquals('2', formatter.inputDigit('2')); ``` -------------------------------- ### Format Phone Numbers with PhoneNumberFormat Enum Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Demonstrates formatting a parsed phone number into different formats using the PhoneNumberFormat enum. Ensure the number is parsed correctly before formatting. ```javascript const { PhoneNumberFormat: PNF, PhoneNumberUtil } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('+33 1 42 68 53 00', 'FR'); console.log(phoneUtil.format(number, PNF.E164)); // => '+33142685300' console.log(phoneUtil.format(number, PNF.INTERNATIONAL)); // => '+33 1 42 68 53 00' console.log(phoneUtil.format(number, PNF.NATIONAL)); // => '01 42 68 53 00' console.log(phoneUtil.format(number, PNF.RFC3966)); // => 'tel:+33-1-42-68-53-00' ``` -------------------------------- ### Parse and Format Phone Number with Browserify Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/test/browser.html Parses a raw phone number string and formats it using the E.164 standard. Requires libphonenumber to be included via Browserify. ```javascript var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance(); var PNF = libphonenumber.PhoneNumberFormat; var phoneNumber = phoneUtil.parseAndKeepRawInput('912345678', 'PT'); console.log(phoneUtil.format(phoneNumber, PNF.E164)); ``` -------------------------------- ### Parse and Validate Phone Number Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Demonstrates the correct way to validate a phone number for a specific region. Ensure the number is parsed into a PhoneNumber object before validation. ```javascript phoneUtil.isValidNumberForRegion(phoneUtil.parse('202-456-1414', 'US'), 'US'); ``` -------------------------------- ### Configure TerserPlugin for US-ASCII Output Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md When compiling with webpack, use this configuration to ensure TerserPlugin outputs US-ASCII characters only, avoiding UTF-8 encoding errors in Chrome extensions. ```javascript optimization: { minimize: process.env.NODE_ENV !== 'development', minimizer: [ new TerserPlugin({ terserOptions: { output: { ascii_only: true } }, }), ] } ``` -------------------------------- ### Access fields of a parsed PhoneNumber object Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Demonstrates how to retrieve various fields such as country code, national number, extension, and Italian leading zero status from a parsed PhoneNumber object. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('202-456-1414', 'US'); const numberRaw = phoneUtil.parseAndKeepRawInput('+44 20 7183 8750', 'GB'); // --- Accessing fields on a parsed PhoneNumber --- console.log(number.getCountryCode()); // => 1 console.log(number.getNationalNumber()); // => 2024561414 console.log(number.getExtension()); // => '' console.log(number.getItalianLeadingZero()); // => false console.log(numberRaw.getRawInput()); // => '+44 20 7183 8750' console.log(number.getCountryCodeSource()); // => FROM_DEFAULT_COUNTRY ``` -------------------------------- ### Format a parsed phone number into different styles Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Format a parsed phone number into E.164, INTERNATIONAL, NATIONAL, and RFC3966 formats using the PhoneNumberUtil. Requires the PhoneNumberFormat enum. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('202-456-1414', 'US'); // --- Formatting --- console.log(phoneUtil.format(number, PNF.E164)); // => '+12024561414' console.log(phoneUtil.format(number, PNF.INTERNATIONAL)); // => '+1 202-456-1414' console.log(phoneUtil.format(number, PNF.NATIONAL)); // => '(202) 456-1414' console.log(phoneUtil.format(number, PNF.RFC3966)); // => 'tel:+1-202-456-1414' ``` -------------------------------- ### Test AsYouTypeFormatter with Invalid Input Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/src/asyoutypeformatter_test.html Tests how the AsYouTypeFormatter handles invalid characters. Ensures that non-digit characters are ignored or handled gracefully. ```javascript var formatter = new i18n.phonenumbers.AsYouTypeFormatter('US'); assertEquals('1', formatter.inputDigit('1')); assertEquals('1a', formatter.inputDigit('a')); assertEquals('1a2', formatter.inputDigit('2')); assertEquals('1a2b', formatter.inputDigit('b')); assertEquals('1a2b3', formatter.inputDigit('3')); ``` -------------------------------- ### Check if Short Number is Possible for a Region Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Use `isPossibleShortNumberForRegion` to check if a parsed phone number is a potentially valid short number when dialed from a specific region. Requires both `ShortNumberInfo` and `PhoneNumberUtil` instances. ```javascript console.log(shortInfo.isPossibleShortNumberForRegion(phoneUtil.parse('123456', 'FR'), 'FR')); // => true ``` -------------------------------- ### Format a phone number using its original input format Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Re-formats a parsed phone number using the original string's formatting style, useful when the raw input is preferred. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const numberRaw = phoneUtil.parseAndKeepRawInput('+44 20 7183 8750', 'GB'); // formatInOriginalFormat — uses the original string's formatting style console.log(phoneUtil.formatInOriginalFormat(numberRaw, 'GB')); // => '+44 20 7183 8750' ``` -------------------------------- ### Check if Short Number Connects to Emergency Services Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Use `connectsToEmergencyNumber` to determine if a given short number can connect to emergency services from a specific region. Requires a `ShortNumberInfo` instance. ```javascript console.log(shortInfo.connectsToEmergencyNumber('911', 'US')); // => true ``` -------------------------------- ### Classify a phone number by type and region Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Determine the type of a phone number (e.g., FIXED_LINE_OR_MOBILE) and retrieve its associated region code. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('202-456-1414', 'US'); // --- Classification --- console.log(phoneUtil.getNumberType(number)); // => FIXED_LINE_OR_MOBILE (PNT) console.log(phoneUtil.getRegionCodeForNumber(number)); // => 'US' ``` -------------------------------- ### Validate Short Codes and Emergency Numbers Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Use ShortNumberInfo to check if a number string connects to an emergency service or is a possible/valid short code for a given region. Requires ShortNumberInfo and PhoneNumberUtil instances. ```javascript const { ShortNumberInfo, PhoneNumberUtil } = require('google-libphonenumber'); const shortInfo = ShortNumberInfo.getInstance(); const phoneUtil = PhoneNumberUtil.getInstance(); // connectsToEmergencyNumber(numberString, regionCode) console.log(shortInfo.connectsToEmergencyNumber('911', 'US')); // => true console.log(shortInfo.connectsToEmergencyNumber('999', 'GB')); // => true console.log(shortInfo.connectsToEmergencyNumber('123', 'US')); // => false // isPossibleShortNumber(PhoneNumber) — takes a parsed PhoneNumber object const fr123 = phoneUtil.parse('123456', 'FR'); console.log(shortInfo.isPossibleShortNumber(fr123)); // => true // isPossibleShortNumberForRegion(PhoneNumber, regionCode) console.log(shortInfo.isPossibleShortNumberForRegion(fr123, 'FR')); // => true console.log(shortInfo.isPossibleShortNumberForRegion(fr123, 'DE')); // => false // isValidShortNumber(PhoneNumber) const usShort = phoneUtil.parse('40404', 'US'); console.log(shortInfo.isValidShortNumber(usShort)); // => true // isValidShortNumberForRegion(PhoneNumber, regionCode) console.log(shortInfo.isValidShortNumberForRegion(usShort, 'US')); // => true console.log(shortInfo.isValidShortNumberForRegion(usShort, 'GB')); // => false ``` -------------------------------- ### Detect Country Code Source Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Determine how the country code was identified during phone number parsing using PhoneNumber.getCountryCodeSource(). Requires PhoneNumberUtil instance. ```javascript const { PhoneNumberUtil } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const withPlus = phoneUtil.parseAndKeepRawInput('+12024561414', 'US'); const withDefault = phoneUtil.parseAndKeepRawInput('2024561414', 'US'); const withIDD = phoneUtil.parseAndKeepRawInput('0112024561414','DE'); console.log(withPlus.getCountryCodeSource()); // => FROM_NUMBER_WITH_PLUS_SIGN console.log(withDefault.getCountryCodeSource()); // => FROM_DEFAULT_COUNTRY console.log(withIDD.getCountryCodeSource()); // => FROM_NUMBER_WITH_IDD // All CountryCodeSource values: // UNSPECIFIED = 0 // FROM_NUMBER_WITH_PLUS_SIGN = 1 // FROM_NUMBER_WITH_IDD = 5 // FROM_NUMBER_WITHOUT_PLUS_SIGN = 10 // FROM_DEFAULT_COUNTRY = 20 ``` -------------------------------- ### Check if Short Number is Possible Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Use `isPossibleShortNumber` to check if a parsed phone number is a potentially valid short number. Requires a `PhoneNumberUtil` instance to parse the number first. ```javascript console.log(shortInfo.isPossibleShortNumber(phoneUtil.parse('123456', 'FR'))); // => true ``` -------------------------------- ### Validate a phone number for correctness and possibility Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Validate if a parsed phone number is generally valid, valid for a specific region, or merely possible (e.g., not too short or too long). ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const number = phoneUtil.parse('202-456-1414', 'US'); // --- Validation --- console.log(phoneUtil.isValidNumber(number)); // => true console.log(phoneUtil.isValidNumberForRegion(number, 'US')); // => true console.log(phoneUtil.isPossibleNumber(number)); // => true ``` -------------------------------- ### Classify Phone Number Types with PhoneNumberType Enum Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Shows how to determine the type of a parsed phone number using the PhoneNumberType enum. This is useful for categorizing numbers like mobile, toll-free, or fixed-line. ```javascript const { PhoneNumberUtil, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const samples = [ { raw: '202-456-1414', region: 'US' }, { raw: '+447700900000', region: 'GB' }, { raw: '+18005551234', region: 'US' }, ]; samples.forEach(({ raw, region }) => { const number = phoneUtil.parse(raw, region); console.log(`${raw}: ${phoneUtil.getNumberType(number)}`); }); // => 202-456-1414: 3 (FIXED_LINE_OR_MOBILE = 3) // => +447700900000: 1 (MOBILE = 1) // => +18005551234: 2 (TOLL_FREE = 2) ``` -------------------------------- ### Comprehensive Phone Number Analysis Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt A utility function to parse, validate, format, and determine the type of a phone number, including error handling for invalid inputs. Combines multiple library features. ```javascript const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT, AsYouTypeFormatter, ShortNumberInfo } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const shortInfo = ShortNumberInfo.getInstance(); function analyzePhoneNumber(rawNumber, defaultRegion) { let parsed; try { parsed = phoneUtil.parseAndKeepRawInput(rawNumber, defaultRegion); } catch (e) { return { error: e.message }; } const isValid = phoneUtil.isValidNumber(parsed); const isPossible = phoneUtil.isPossibleNumber(parsed); return { raw: rawNumber, region: phoneUtil.getRegionCodeForNumber(parsed), countryCode: parsed.getCountryCode(), nationalNumber: String(parsed.getNationalNumber()), e164: isValid ? phoneUtil.format(parsed, PNF.E164) : null, international: isValid ? phoneUtil.format(parsed, PNF.INTERNATIONAL) : null, national: isValid ? phoneUtil.format(parsed, PNF.NATIONAL) : null, rfc3966: isValid ? phoneUtil.format(parsed, PNF.RFC3966) : null, isValid, isPossible, type: phoneUtil.getNumberType(parsed), }; } console.log(analyzePhoneNumber('202-456-1414', 'US')); // => { // raw: '202-456-1414', // region: 'US', // countryCode: 1, // nationalNumber: '2024561414', // e164: '+12024561414', // international: '+1 202-456-1414', // national: '(202) 456-1414', // rfc3966: 'tel:+1-202-456-1414', // isValid: true, // isPossible: true, // type: 3 // FIXED_LINE_OR_MOBILE // } console.log(analyzePhoneNumber('123', 'US')); // => { ..., isValid: false, isPossible: false, e164: null, ... } console.log(analyzePhoneNumber('111111111111111111111', 'US')); // => { error: 'The string supplied is too long to be a phone number' } // Live input UI simulation const formatter = new AsYouTypeFormatter('US'); const liveInput = '2024561414'; console.log('Live formatting:'); liveInput.split('').forEach(d => console.log(' ', formatter.inputDigit(d))); // => 2 → 20 → 202 → 202-4 → ... → (202) 456-1414 // Emergency number check console.log(shortInfo.connectsToEmergencyNumber('911', 'US')); // => true ``` -------------------------------- ### Incorrect Phone Number Validation Source: https://github.com/ruimarinho/google-libphonenumber/blob/master/README.md Illustrates an incorrect method for validating a phone number. Passing a raw string instead of a parsed PhoneNumber object will result in an error. ```javascript phoneUtil.isValidNumberForRegion('202-456-1414', 'US'); ``` -------------------------------- ### Parse phone number while retaining original input string Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt Use parseAndKeepRawInput to parse a phone number and preserve the original input string, which can be useful for formatting or display. ```js const { PhoneNumberUtil, PhoneNumberFormat: PNF, PhoneNumberType: PNT } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); // parseAndKeepRawInput(numberString, defaultRegion) — retains the original string const numberRaw = phoneUtil.parseAndKeepRawInput('+44 20 7183 8750', 'GB'); ``` -------------------------------- ### CountryCodeSource Enum Source: https://context7.com/ruimarinho/google-libphonenumber/llms.txt The CountryCodeSource enum indicates how the country code was determined when parsing a phone number. This information is accessible via the getCountryCodeSource() method on a PhoneNumber object. ```APIDOC ## CountryCodeSource — Country Code Detection Enum Indicates how the country code was determined when parsing a number, accessible via `PhoneNumber.getCountryCodeSource()`. ### Enum Values - **UNSPECIFIED** (0): The source of the country code is not specified. - **FROM_NUMBER_WITH_PLUS_SIGN** (1): The country code was derived from a number starting with a plus sign (+). - **FROM_NUMBER_WITH_IDD** (5): The country code was derived from a number using an International Direct Dialing (IDD) prefix. - **FROM_NUMBER_WITHOUT_PLUS_SIGN** (10): The country code was derived from a number without a leading plus sign. - **FROM_DEFAULT_COUNTRY** (20): The country code was inferred from the default region. ### Example Usage ```js const { PhoneNumberUtil } = require('google-libphonenumber'); const phoneUtil = PhoneNumberUtil.getInstance(); const withPlus = phoneUtil.parseAndKeepRawInput('+12024561414', 'US'); const withDefault = phoneUtil.parseAndKeepRawInput('2024561414', 'US'); const withIDD = phoneUtil.parseAndKeepRawInput('0112024561414','DE'); console.log(withPlus.getCountryCodeSource()); // => FROM_NUMBER_WITH_PLUS_SIGN console.log(withDefault.getCountryCodeSource()); // => FROM_DEFAULT_COUNTRY console.log(withIDD.getCountryCodeSource()); // => FROM_NUMBER_WITH_IDD ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.