How to create phone number validator rules that catch common errors

Content authorBy Claire ConnorPublished onReading time9 min read
Title:
How to create phone number validator rules that catch common errors

Meta description:
Learn how a phone number validator lets you clean input and check whether numbers can receive messages.

A

Turning messy phone input into stored numbers you can actually message means building a validation pipeline, not a single regex. From cleaning through to a live network lookup, then what to return to the caller and how to test the whole thing end to end.

Why regex falls short

Most teams start with a pattern match, and eventually learn that a phone number validator built only on regex accepts numbers that don't exist. Any ten digits with plausible spacing can pass almost every homegrown expression.

"Is this number valid?" is actually three separate questions: formatting, numbering-plan validation, and reachability. Regex only answers the first.

Set the E.164 standard

Before you write a phone number validator rule, decide what a correct stored value looks like. Pick E.164 and enforce it everywhere: a leading plus sign and the national number with its trunk prefix removed.

The ceiling matters. The ITU caps a conforming number at 15 digits excluding the international prefix, with the country code taking one to three of those and the national significant number filling the remainder. Anything longer isn't a phone number, whatever your form accepts.

E.164 is a storage format. If you want pretty output on an invoice or a letterhead, ITU-T Recommendation E.123 covers spacing conventions for that. Keep the two jobs apart. One canonical value in the database, formatted views generated on demand.

This pays off because two records holding +44XXXXXXXX and XXX-XXX-XXXX might look like two different customers to your CRM, but they collapse to the same E.164 string. Deduplication is a side effect of proper normalisation.

Build phone number validator rules

Infographic illustrating a phone number validation pipeline with 'Raw Input', 'Clean Input', and 'Validate Number' sections, ending in 'Accepted' and 'Reject…

The order of operations decides whether your phone number validator rules work. Judge the input before you've cleaned it, and you'll reject good numbers on cosmetic grounds while letting structurally impossible ones through. Run the pipeline in this sequence, and never let a later stage compensate for one you skipped.

Clean raw input

Raw phone input is rarely clean. Users paste from spreadsheets, email signatures, and Word documents. Strip whitespace and the em dashes that Word substitutes for hyphens without asking.

Invisible characters are the ones that waste an afternoon. Zero-width spaces and directional overrides survive a copy-paste, and none of them show up in your logs. The Cloud Security Alliance recommends stripping zero-width characters in the U+200B to U+200D range along with U+FEFF and bidirectional controls before any downstream processing.

Full-width digits are the other quiet failure. A number typed on a Japanese or Korean input method produces characters like 3 (U+FF13), which looks identical to 3 and matches none of your digit patterns. Apply NFKC normalization, which maps full-width forms to ASCII by design.

Extensions need care. When you find "ext", "x", or "#" followed by digits, split at that boundary and hold the extension aside.

Validate every number. Deliver every message.

Talk to our team about real-time phone number validation, fraud prevention, and high-deliverability SMS for your business.

Normalize the format

You now have a digit string plus an optional extension. Reduce it to one representation before you judge anything. That means deciding what a leading "00" means and what a leading "+" means.

A "00" prefix is an international access code. Though there are exceptions to this rule, Google's own FAQ on international prefixes notes that Ascension Island uses 00 the same way, but plenty of countries don't, which is one more reason to defer to library metadata.

Keep the extension in its own field from here forward. It never belongs inside the E.164 string, and it never goes to a network lookup.

Resolve the country

This is where most implementations quietly break. A bare national number carries no country information, and treating every unprefixed string as UK input is a decision, not a default. It's the wrong decision for anyone whose number sits outside the UK's own numbering plan.

Rank your sources of country context and use them in order:

  • The explicit country code the user selected in the form, which is the safest signal because the person entering the number told you

  • The country stored on the account, the billing address, or the shipping record already in your system

  • The number's own prefix when it arrives with a plus sign, in which case you don't need to infer anything

Never guess from an IP address. Someone signing up from a hotel in Edinburgh with a German mobile will be assigned +44 by that logic, and you'll spend the next six months wondering why their alerts vanish. If you can't establish country with confidence, return an error asking for it.

Remove trunk prefixes

The trunk prefix is the digit you dial before a national number inside a country, and it doesn't belong in the international form. UK mobile numbers carry ten national significant digits after the trunk code 0, so 0XXXX XXXXXX becomes +44XXXXXXXXXX. Not +4407XXXXXXXXX, which is unroutable and one of the most common errors in stored contact data.

Do not write a rule that removes every leading zero, because Italy retains it. Strip the zero, and you've destroyed a valid number. That's the argument against maintaining trunk rules by hand. Every country has its own convention, and your regex won't hear about it.

Check if a number is possible

Feed the country and the cleaned-up number to a trusted, well-maintained library. Google's libphonenumber offers two kinds of checks. One just looks at whether the number is the right length, while the other actually checks the number against the region's rules in more detail.

Which should you use? The person behind a popular JavaScript version of the library argues for the simpler, looser check. His reasoning: the stricter check depends on data that needs constant updates. If that data goes stale, the library starts rejecting real numbers that were only recently issued. That's a real risk if you install the library once and never update it: Google updates the data roughly every two weeks for most of the year.

The safest approach is to run both checks and treat the results differently:

  • If a number fails the basic check, reject it outright

  • If it passes the basic check but fails the detailed one, flag it for review. It might belong to a number range that was allocated recently and hasn't made it into the data yet.

Validate every number. Deliver every message.

Talk to our team about real-time phone number validation, fraud prevention, and high-deliverability SMS for your business.

Run an HLR lookup

Structural validity ends here. The number is well-formed, and it fits its country's plan. An HLR lookup provides a point-in-time network-level signal about whether a mobile number appears active, inactive, unreachable, ported, roaming or unknown, depending on market and data availability.

Send the normalised E.164 string to a service such as Acudo and read the network response. An HLR lookup returns response codes, and the codes that carry most of the weight report whether the number is live and reachable. Format validation catches roughly 70 to 80 percent of bad numbers, the cheap and obvious ones, while a live network check removes the disconnected and non-mobile lines that pass a format check cleanly.

Treat the result as a point-in-time answer. A number that appears active today can be disconnected, reassigned, or changed later, so validate at entry and revalidate before large or important sends.

Return useful validation results

A boolean is the wrong return type. Your caller needs to know why something failed, because the fix for each failure is different. Define four outcomes and return the reason alongside them.

  1. Malformed: cleaning produced something that isn't a number, or the extension parse failed

  2. Impossible: the digit count or prefix can't exist in the resolved country

  3. Structurally valid: no network check performed or the check was inconclusive

  4. Unsuitable or unreachable: structurally correct, but line-type or network-level checks indicate the number is inactive, unreachable, non-mobile or otherwise unsuitable for the intended communication.

Alongside the verdict, store the raw input exactly as it arrived and the normalised E.164 result as separate fields. E.164 is the international standard format for phone numbers: a plus sign, country code, and subscriber number with no spaces or punctuation. Do not overwrite the raw value before the normalised result has been reviewed and mapped correctly, because if normalization goes wrong and the original is gone, you have no way back.

Silent transformation is the failure mode to avoid. If your pipeline had to guess a country, say so in the result. A record that quietly became a UK number because nobody supplied context will pass every check you run and fail every message you send.

Add real-time feedback

Timing is the whole game with inline validation for a phone number validator. Baymard Institute's testing found that when validation fires too early, participants' typing was disrupted as they stopped to read an error, and some concluded their perfectly valid input was wrong. Validate when the field loses focus, or once enough digits exist to make a judgment.

Once an error is showing, though, the rules invert. Baymard's recommendation is that the message must live-update on a keystroke level and disappear the moment the input becomes valid. Nothing frustrates a person faster than a corrected field still shouting at them.

Put the correction next to the field while the number and the country selector are both still on screen. "This looks too short for the United Kingdom" gives someone a route forward. "Invalid phone number" gives them a reason to leave.

Test phone number validator rules

Build a fixture file and run it in continuous integration, because these phone number validator rules break silently when a dependency updates or someone refactors the cleaning step. Cover the cases that actually appear in production data.

Feed in an invalid country code and confirm the resolution step fails cleanly instead of throwing. Then include a well-formed number that no carrier has assigned. Ofcom reserves 07700 900000–07700 900999 for fictitious use in TV, film, and fiction, so a number in that range passes structural validation and is caught only by your reachability layer, which makes it a precise test of whether that layer is wired up at all.

Where validation earns its keep

The phone number validator rules in this article stack: cleaning removes the noise, and the network check answers the only question that matters before you send.

Acudo is a specialist validation partner that confirms whether numbers are correctly formatted and whether they reach real, active subscribers, without the overhead of full CPaaS complexity. Speak to Acudo about mobile validation workflows if your phone number validator needs to prove reachability.

Validate every number. Deliver every message.

Talk to our team about real-time phone number validation, fraud prevention, and high-deliverability SMS for your business.

No. Store the main number as E.164 and keep the extension in a separate field. E.164 identifies the public telephone number, while an extension routes a call after it reaches a private phone system. Send only the normalized main number to SMS or reachability checks.

Recheck numbers before high-value or large-scale communications, because reachability changes after a subscriber disconnects or changes service. Recheck a record after a delivery failure as well. Keep the date and result of each lookup so your team can distinguish an old result from a current one.

Ask the person to select a country before you normalize a national-format number. A bare digit string doesn't identify its numbering plan, so an inferred country can produce a wrong E.164 value. Record the country source, such as form selection or account address, with the validation result.

A phone number validator can confirm formatting and numbering-plan rules without confirming that a live subscriber uses the number. Disconnected lines and fictitious ranges can pass structural checks. Run a network lookup when message reachability affects the decision, then treat its result as time-sensitive.

Yes. Acudo can check a normalized mobile number against live network information to identify reachability status. Use that result after format and numbering-plan checks, especially before critical communications. Speak to Acudo about mobile validation workflows if your system needs network-level confirmation.

Get in touch

Talk to our team about phone number validation, fraud prevention, and reliable SMS communications.

You Might Also Like

Discover more insights and articles

A realistic smartphone in a hand displays a phone number entry UI, glowing network overlay, and a secure checkmark, with warm bokeh background.

Phone verification for trust & safety teams

Fake accounts are rarely stopped by adding another verification step. The better approach is to use phone intelligence to decide which signups need more friction and which can pass with minimal interruption.

For trust & safety teams, the goal is not to verify every phone number in the same way. It is to identify numbers that look risky, validate legitimate ones quickly, and reserve stronger verification for accounts that show other signs of abuse.

A close-up of a realistic hand holding a smartphone displaying a UK phone number signup interface with a glowing network overlay.

How to set up UK phone number verification

A UK mobile number can look perfectly valid and still be unsuitable for an OTP, onboarding check, or critical customer message. The problem is what happens between accepting the number and sending the message: format validation can confirm that the number follows UK numbering rules, but it cannot tell you everything about the line itself. A stronger verification flow puts number validation and intelligence before the OTP send, so product, engineering, and trust & safety teams can make a better decision about whether to proceed.

A realistic hand holds a glossy smartphone displaying an SMS campaign dashboard, with glowing network icons and warm bokeh background.

How to build a bulk SMS messaging campaign that drives results

A first bulk SMS messaging campaign either sets the pattern for every one that follows, or teaches an expensive lesson in consent and list hygiene before a single message goes out. Getting it right comes down to sequence: one measurable goal, defensible consent, a validated list, and a message worth reading, built on the UK rules that decide whether a text lands or gets filtered.

A realistic hand holds a smartphone displaying a glowing network map, surrounded by icons and a warm, blurred bokeh background.

Understanding phone number data for customer outreach

Phone number data carries attributes that shape calling and messaging decisions, and even a careful cleanup leaves records that go stale over time. A layered validation workflow addresses this directly.