Validate a Nigerian phone number in JavaScript
Intermediate · 4 min read
Ask a hundred people in Nigeria for their phone number and you'll get it typed many ways: 08031234567, 0803 123 4567, +2348031234567, (0803) 123-4567. They're all the same number. A sign-up form needs to accept every one of them, store them in one consistent form, and still reject things that aren't mobile numbers at all.
In this tutorial you will write two functions: normalisePhone, which turns any of those spellings into the local form 08031234567, and isMobile, which checks the result. You should know what strings and functions are. Regular expressions are explained from the start.
The shape of a local mobile number
A Nigerian mobile number in local form is eleven digits:
- A
0at the start (called the trunk zero). - A network pair:
70,71,80,81,90or91. - Eight more digits.
In international form, the trunk zero is replaced by the country code 234, often with a + in front: +234 803 123 4567.
Normalize first, then check
You could try to write one pattern that allows spaces, hyphens, brackets, a plus, a country code and an optional zero. It would be unreadable. The cleaner plan has two parts:
- Normalize: reduce every spelling to one standard form.
- Validate: check that one form against one simple pattern.
A bonus: everything you save is then in the same form, so comparing two numbers is just ===.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
114 Validate a Nigerian mobile number
fairAccept a mobile number however it was typed — 08031234567, 0803 123 4567, +2348031234567 — normalise it to the local form, and reject what is not a mobile number at all. Also exercise 49, which validated an email honestly; the same honesty applies here.
Stuck? Three hints, smallest first
- 1. Normalise first, validate second. One shape to check beats five patterns.
- 2. A local mobile number is eleven digits: a zero, then 70, 71, 80, 81, 90 or 91, then eight more.
- 3. The country code may or may not be followed by the trunk zero, so do not add a second one.
Step 1: remove spaces, brackets and hyphens
const raw = ' (0803) 123-4567 ';
const digits = raw.trim().replace(/[\s()-]/g, '');
console.log(digits); // 08031234567
/[\s()-]/g is a regular expression, a search pattern. The square brackets mean "any one of these characters": a whitespace character (\s), (, ) or -. The g at the end means "every match", so replace swaps all of them for nothing.
Step 2: strip the country code
let digits = '+2348031234567';
if (digits.startsWith('+')) digits = digits.slice(1);
if (digits.startsWith('234')) digits = digits.slice(3);
console.log(digits); // 8031234567
slice(1) drops the first character and slice(3) drops the first three. We now have the number without its trunk zero.
Step 3: put the zero back, but only once
The natural next line is "add a 0 in front". But some people write the country code and keep the zero: +234 0803 .... After stripping 234 that one already starts with 0. Adding another would give 008031234567.
So the zero is added only when it's missing:
function normalisePhone(raw) {
let digits = String(raw).trim().replace(/[\s()-]/g, '');
if (digits.startsWith('+')) digits = digits.slice(1);
if (digits.startsWith('234')) digits = digits.slice(3);
if (!digits.startsWith('0')) digits = '0' + digits;
return digits;
}
console.log(normalisePhone('+2348031234567')); // 08031234567
console.log(normalisePhone('2348031234567')); // 08031234567
console.log(normalisePhone('23408031234567')); // 08031234567
console.log(normalisePhone('0803 123 4567')); // 08031234567
Four spellings, one result.
Step 4: the pattern for one shape
Now the check only has to describe the local form:
const pattern = /^0[789][01]\d{8}$/;
console.log(pattern.test('08031234567')); // true
console.log(pattern.test('08531234567')); // false
Read it piece by piece:
^and$mean the start and end of the text, so nothing extra can sit on either side.0is the trunk zero.[789]is one digit that is 7, 8 or 9, and[01]is one digit that is 0 or 1. Together they allow exactly the six network pairs.\d{8}is exactly eight digits.
test returns true when the text matches. 085 fails because 5 isn't 0 or 1.
Step 5: put the two together
function normalisePhone(raw) {
let digits = String(raw).trim().replace(/[\s()-]/g, '');
if (digits.startsWith('+')) digits = digits.slice(1);
if (digits.startsWith('234')) digits = digits.slice(3);
if (!digits.startsWith('0')) digits = '0' + digits;
return digits;
}
const isMobile = (raw) => /^0[789][01]\d{8}$/.test(normalisePhone(raw));
console.log(isMobile('(0803) 123-4567')); // true
console.log(isMobile('0803123456')); // false: ten digits
console.log(isMobile('0803abc4567')); // false: letters
console.log(isMobile('08000000000')); // true
The last line is the honest limit of this check. 08000000000 has the right shape, so it passes, but nobody owns it. A pattern can only check shape. The only way to prove a number is real is to send a one-time code to it and ask the person to type it back.
Stripping 234 is a guess, too. Any input that really began with the digits 234 for another reason would be cut wrongly. That's the price of accepting so many spellings.
The full solution
The answer panel has normalisePhone and isMobile, prints a small table of inputs, and checks the cleaned forms, the international forms, the extra trunk zero, a short number, letters, an unused network pair and the well-formed number nobody owns. Press Run to see the output.
function normalisePhone(raw) {
let digits = String(raw).trim().replace(/[\s()-]/g, '');
if (digits.startsWith('+')) digits = digits.slice(1);
if (digits.startsWith('234')) digits = digits.slice(3);
if (!digits.startsWith('0')) digits = '0' + digits;
return digits;
}
// Eleven digits: 0, a network pair from 70/71/80/81/90/91, then eight more.
const isMobile = (raw) => /^0[789][01]\d{8}$/.test(normalisePhone(raw));
for (const n of ['08031234567', '0803 123 4567', '+2348031234567', '2348031234567', '08531234567']) {
console.log(String(n).padEnd(16), normalisePhone(n).padEnd(13), isMobile(n));
}
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a number as most people type it', isMobile('08031234567'), true);
test('spaces and brackets are cleaned off first', isMobile('(0803) 123-4567'), true);
test('the international form normalises to the local one', normalisePhone('+2348031234567'), '08031234567');
test('so does the country code without the plus', normalisePhone('2348031234567'), '08031234567');
test('and a country code that kept the trunk zero is not given a second', normalisePhone('23408031234567'), '08031234567');
test('ten digits is one short', isMobile('0803123456'), false);
test('letters are not digits', isMobile('0803abc4567'), false);
test('an unissued network pair is refused', [isMobile('08531234567'), isMobile('012345678')], [false, false]);
test('but a well-formed dead number passes, because shape is all this checks', isMobile('08000000000'), true);
Normalise then validate. The alternative — one pattern that tolerates spaces, hyphens, brackets, a leading plus, a country code and an optional trunk zero — is unreadable and impossible to extend, and it leaves the caller holding whichever of five formats arrived. Reducing every input to a single canonical form means the regex describes one shape, and everything downstream compares and stores that shape.
The trunk zero is the edge that catches people. +234 803 ... drops the zero and +234 0803 ... keeps it, both are written in the wild, and blindly prepending a zero after stripping 234 gives 00803.... The prefix sniffing is a heuristic, not a parse: a number that genuinely begins with the digits 234 would be mangled, which is the price of guessing. And as with the email in exercise 49, the last assertion is the lesson — 08000000000 is perfectly formed and belongs to nobody. Only a one-time code sent to the line proves it exists.
Common mistakes
- One giant pattern for every spelling. Normalize first; then the pattern only describes one shape.
- Always adding the zero.
+234 0803...would become00803.... Add it only if it's missing. - Leaving out
^and$. Without them, a match anywhere inside a longer string would pass.
Try it yourself
- Write
toInternational(raw)that returns'+2348031234567'for any spellingnormalisePhoneaccepts. - Add dots as a separator, so
'0803.123.4567'is accepted too. - Write
formatPhone(raw)that returns'0803 123 4567'for a valid number and''for an invalid one.