Drew
Drew

Reputation: 497

How to find the valid phone number length given a Country and PhoneType, using libphonenumber-js

I'm using the libphonenumber-js library from CDN jsdelivr

https://cdn.jsdelivr.net/npm/libphonenumber-js/bundle/libphonenumber-js.min.js

Given I have a valid CountryCode (eg AU) and a PhoneType of mobile or fixed line, is there some way I can find the numeric length of a valid phone number for that type and country?

Upvotes: 0

Views: 392

Answers (1)

wajeeh
wajeeh

Reputation: 1

import { parsePhoneNumberFromString, isValidPhoneNumber } from 'libphonenumber-js';

function getMaxPhoneNumberLengthForCountry(countryCode) {
let maxLength = 0;
let isValid = true;

// Start with a valid prefix for the country, assuming '1' is a valid starting digit for simplicity.
let phoneNumber = '1';

while (isValid) {
    const parsedNumber = parsePhoneNumberFromString(phoneNumber, countryCode);
    
    if (parsedNumber && isValidPhoneNumber(phoneNumber, countryCode)) {
        maxLength = phoneNumber.length;
        phoneNumber += '1'; // Increase the length of the phone number
    } else {
        isValid = false;
    }
}

return maxLength;

}

Upvotes: 0

Related Questions