Skip to content

Blog

Validate phone numbers in JavaScript: libphonenumber-js in the browser, an API on the server

Validate phone numbers in JavaScript: parse with libphonenumber-js, format as the user types, store E.164, then confirm on your server with an API call.

Updated 2026-11-24

Validating a phone number in JavaScript takes three steps: parse what the user typed with a country, check that the result is valid, and store the E.164 form. A parser such as libphonenumber-js does this in the browser or in Node. Run it in the form for fast feedback, then repeat it on your server, where you can also add what a library cannot know: the line type from a live lookup, rate limits and a one-time code.

What a parser does and does not decide

Question Library answer Where it comes from
Is this a phone number, and for which country? Yes, through parsePhoneNumber The input, a + prefix or the defaultCountry you pass
Is the length allowed? isPossible() The country's length rules
Do the digits fit an opened range? isValid() The country's patterns, in the max metadata
What kind of line? getType() Range patterns, in the max metadata
Which network serves it today? Not available A lookup against live data
Does the user hold the phone? Not available A one-time code

A library reads static data. Anything below the third row needs your server. Phone number validation explains the same layers without code.

Install and choose a build

bash
npm install libphonenumber-js

The package comes in four builds, and the choice changes what isValid() means. The default min build ships a smaller dataset. Its README says that min leaves out the precise patterns for the digits, so isValid() effectively behaves like isPossible(), and that getType() can return undefined for most countries. The max build adds both. The README gives sizes of about 80 kB for min and about 65 kB more for max. Check the current README for figures, since releases change them.

Our advice: import from libphonenumber-js/max when you want the answer to mean what it says.

Parse and validate

parsePhoneNumberWithError throws a ParseError whose message is the reason, which beats a silent undefined when you need to explain a failure. Pass extract: false so that the whole string must be a number: by default the library digs a number out of surrounding text, so Call (415) 555-0123 would parse.

javascript
import { parsePhoneNumberWithError, ParseError } from 'libphonenumber-js/max'

export function checkPhone(input, country) {
  let phone
  try {
    phone = parsePhoneNumberWithError(input, { defaultCountry: country, extract: false })
  } catch (error) {
    if (error instanceof ParseError) return { ok: false, reason: error.message }
    throw error
  }
  if (!phone.isPossible()) return { ok: false, reason: 'IMPOSSIBLE_LENGTH' }
  if (!phone.isValid()) return { ok: false, reason: 'NOT_VALID' }
  return {
    ok: true,
    e164: phone.number,
    country: phone.country,
    type: phone.getType() ?? null,
    national: phone.formatNational(),
    ext: phone.ext ?? null,
  }
}

We ran this function with libphonenumber-js 1.13.17. The table shows what came back.

Input Country Result
(415) 555-0123 US ok, +14155550123, type FIXED_LINE_OR_MOBILE
07400 123456 GB ok, +447400123456, type MOBILE
07400 123456 none INVALID_COUNTRY
abc US NOT_A_NUMBER
Call (415) 555-0123 US NOT_A_NUMBER, because of extract: false
+44 7400 12345 none NOT_VALID: possible length, not a valid UK mobile
+1 123 456 7890 none NOT_VALID: area codes never start with 1
(415) 555-0123 ext. 7 US ok, ext is 7, e164 has no extension
415 US IMPOSSIBLE_LENGTH
+999 123 none INVALID_COUNTRY: no such calling code

Three details matter in practice.

  • Extensions stay apart. phone.number is the E.164 number without the extension, and phone.ext holds it. E.164 has no place for an extension, so store it in its own column.
  • FIXED_LINE_OR_MOBILE is normal in North America. The plan does not separate the two, so do not treat it as a failure.
  • The international prefix depends on the default country. A number typed with 00 is read as international when the default country uses 00, and a US default does not. The phone API reads 00 like + for any country. If your users type 00, send the + form from the browser.

Give a better reason than "invalid"

Map the errors to messages people can act on. validatePhoneNumberLength returns a more precise length reason, such as TOO_SHORT, TOO_LONG or INVALID_LENGTH, or nothing when the length is allowed.

javascript
import { validatePhoneNumberLength } from 'libphonenumber-js/max'

const messages = {
  INVALID_COUNTRY: 'Choose the country of this number.',
  NOT_A_NUMBER: 'Enter digits only, with an optional + at the start.',
  TOO_SHORT: 'This number is too short for the country.',
  TOO_LONG: 'This number is too long for the country.',
  INVALID_LENGTH: 'This number has a length the country does not use.',
  NOT_VALID: 'This number does not exist in the numbering plan. Check the digits.',
}

export function explain(input, country) {
  const lengthProblem = validatePhoneNumberLength(input, country)
  if (lengthProblem) return messages[lengthProblem]
  return null
}

Show an example number for the selected country beside the error. getExampleNumber from the same package, with the libphonenumber-js/mobile/examples data, returns one.

Format as the user types

AsYouType formats a partly typed number. With a country it writes the national format, and without one it expects the international + form.

javascript
import { AsYouType } from 'libphonenumber-js'

const field = document.querySelector('#phone')
const country = document.querySelector('#country')

field.addEventListener('blur', () => {
  field.value = new AsYouType(country.value).input(field.value)
})

Format on blur instead of on every keystroke. Rewriting the value while someone types moves the caret and fights the keyboard on phones. In our run, new AsYouType('US').input('4155550123') returned (415) 555-0123.

For the form's autocomplete, use tel and set inputmode="tel" so mobile keyboards show the dial pad. Do not use type="number": it drops the + and leading zeros.

Store E.164, not what was typed

Keep phone.number and the country. Two spellings of one number then match, and SMS providers accept the value as it is. A text column is the right type: a numeric column drops the +. See E.164 explained, and format phone numbers to E.164 in a sheet for an existing list.

javascript
import parsePhoneNumber from 'libphonenumber-js/max'

const a = parsePhoneNumber('(415) 555-0123', 'US')
const b = parsePhoneNumber('+1 415 555 0123')
console.log(a.number === b.number, a.isEqual(b))

The log prints true true: both spellings give one E.164 string, and isEqual compares two parsed numbers.

Repeat the check on your server, and add a lookup

The browser result is a convenience. A script can post anything to your endpoint, so validate again on the server and then ask the API for what the library cannot give you: a line type confirmed by a lookup, the carrier and a live check where it matters.

javascript
const API = 'https://api.qelka.com/v1'

export async function lookupPhone(e164) {
  let response
  try {
    response = await fetch(`${API}/phone`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${process.env.API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ phone: e164 }),
      signal: AbortSignal.timeout(5000),
    })
  } catch {
    return { decision: 'accept_unchecked' }
  }
  if (!response.ok) return { decision: 'accept_unchecked' }

  const result = await response.json()
  if (!result.valid) return { decision: 'ask_correction' }
  if (['premium_rate', 'shared_cost'].includes(result.line_type)) return { decision: 'refuse' }
  return { decision: 'accept', e164: result.e164, lineType: result.line_type }
}

The call fails open: when the API is slow or unreachable the form goes through and you can check later. A validation outage should not stop signups. The key must stay on the server, as a key in browser code can be read and spent by anyone. A basic check costs 1 credit, and "level": "live" adds the current carrier and the ported flag for 3 credits.

With the official client the same call is shorter, and it retries rate-limited requests for you:

javascript
import { Client } from '@qelka/sdk'

const client = new Client({ apiKey: process.env.API_KEY })
const phone = await client.phone.validate({ phone: '(415) 555-0123', country: 'US' })
if (phone.valid) console.log(phone.e164, phone.line_type)

JavaScript SDK lists every method, and the phone API reference describes each field. Pass an sk_test_ key in development: test mode parses numbers for real and spends no credits. For Node frameworks see the Node.js, Express and Next.js pages.

Why not rely on the library alone

Library alone Library plus API
Static data bundled in your app The same plan data, kept current on the server
No view of the network Live level: current carrier, mobile codes, ported
Runs where users can bypass it Runs where you control it
Line type from range patterns only The provider's line type on the live level
You update the package for new ranges The server updates for you

The metadata inside any library is a snapshot. Regulators open new ranges, and a validator that is not updated can reject numbers that have just been assigned. The README of libphonenumber-js says as much: its author would personally prefer isPossible(), because isValid() can go stale when the data is not kept up to date and then reject freshly assigned ranges. If a customer says a new number is real, believe them, and check the range with the regulator.

Mistakes that cost the most

  • A fixed default country. Take it from a selector or the locale. A US default fails every French number typed at home.
  • The default build with isValid(). It checks little more than length. Import from /max.
  • Parsing without extract: false in a form. Call me on 415... passes and stores junk.
  • Storing the typed string. Store E.164.
  • Calling the API from the browser. Your key leaks.
  • Sending a code before validating. Each SMS costs money. SMS pumping fraud shows why.

Try the free phone validator to compare your results, and read libphonenumber: what the library knows and what it does not for the data behind it.

Frequently asked questions

How do I validate a phone number in JavaScript?
Install libphonenumber-js, parse the input with the user's country, then call isPossible() and isValid() on the result. Import from libphonenumber-js/max, because the default build ships looser metadata. Store phone.number, which is the E.164 form. Then repeat the check on your server, since anything that runs in the browser can be skipped by a script.
What is the difference between isPossible and isValid in libphonenumber-js?
isPossible() checks only the length against what the country allows. isValid() also checks the digits against the country's number patterns. With the default min metadata, isValid() behaves almost like isPossible(), because that build leaves out the precise patterns. Use the max build when you want a real validity check, and accept that stricter data can lag behind newly opened ranges.
Do I need a country to parse a phone number?
Only when the number has no leading +. With a + and a country calling code the library can read the number alone. Without it, pass defaultCountry, usually taken from a country selector or the visitor's locale. Without either, parsing fails with INVALID_COUNTRY, which is the right outcome: the digits alone do not name a country.
Should I validate phone numbers on the client or the server?
Both, for different jobs. On the client, a parser gives instant feedback and formats as people type. On the server, you repeat the check and add what a library cannot know: the line type from a lookup, the current carrier and rate limits. Never trust the browser's result, because it runs on a machine you do not control.
How big is libphonenumber-js?
It depends on the build. The README of libphonenumber-js puts the default min metadata at about 80 kB and says the max build, which adds precise validation and line types, costs roughly 65 kB more. Sizes change between releases, so check the current README. If bundle size matters, validate length in the browser and run the full check on the server.
How do I get the line type of a phone number in JavaScript?
Call getType() on a parsed number, imported from the max build. It returns values such as MOBILE, FIXED_LINE and FIXED_LINE_OR_MOBILE, or undefined when the metadata has no pattern for the country. It describes the range the number belongs to, not the current network. For the live carrier, call an API with a lookup level.

Put this check in your product

Get an API key in under a minute. 100 free credits every month, no card required.

  • 100 free credits a month
  • No card
  • Test keys spend nothing
  • Cancel any time