Validate a Nigerian car plate number in JavaScript
Intermediate · 3 min read
Vehicle registration forms, parking apps and fleet trackers all ask for a plate number. A Nigerian plate looks like KJA-234-XY: three letters, three digits, two letters. People will type it as kja 234 xy, KJA234XY or Kja-234-xy, and your app should accept all of them and show it back the same tidy way every time.
In this tutorial you will write three small functions: normalisePlate to clean the input, isPlate to check it, and formatPlate to print it in the standard hyphenated form. You should know what strings and functions are. The regular expressions are explained as we go.
The same plan as a phone number
Trying to write one pattern that accepts every possible spelling gets messy fast. The cleaner plan:
- Normalize: uppercase the input and remove everything that isn't a letter or a digit.
- Validate: check the cleaned text against one simple pattern.
- Format: add the hyphens back in the right places.
Because the checker and the formatter both start from the same cleaned text, they can't disagree about what a plate is.
Reading a pattern
A regular expression is a search pattern written between slashes. Here are the pieces this lesson needs:
[A-Z]is one capital letter.[0-9]is one digit.{3}after something means "exactly three of those".^is the start of the text and$is the end.[^A-Z0-9], with^inside the brackets, means "any character that is not a capital letter or a digit".
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
115 Validate and format a plate number
fairCheck a Nigerian plate number — three letters, three digits, two letters, as in KJA-234-XY — accepting it typed in lowercase, with spaces, or with no separators at all. Print it back in the canonical hyphenated form.
Stuck? Three hints, smallest first
- 1. Strip everything that is not a letter or a digit, uppercase, then match one pattern.
- 2. The letter slots must be letters: a zero typed for the letter O has to fail.
- 3. Formatting is three slices with hyphens between them.
Step 1: clean the input
const normalisePlate = (raw) => String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '');
console.log(normalisePlate('kja 234 xy')); // KJA234XY
console.log(normalisePlate('KJA-234-XY')); // KJA234XY
toUpperCase() comes first, so lowercase letters become capitals and survive the next line. Then replace with the g (global) flag removes every character that isn't a capital letter or digit: spaces, hyphens, dots, anything.
Step 2: one pattern
const PLATE = /^[A-Z]{3}[0-9]{3}[A-Z]{2}$/;
console.log(PLATE.test('KJA234XY')); // true
console.log(PLATE.test('KJA23XY')); // false
console.log(PLATE.test('123KJAXY')); // false
Three capital letters, three digits, two capital letters, and nothing else before or after. test returns true or false. Two digits where three belong fails, and digits in the letter slots fail.
Step 3: check any spelling
const PLATE = /^[A-Z]{3}[0-9]{3}[A-Z]{2}$/;
const normalisePlate = (raw) => String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '');
const isPlate = (raw) => PLATE.test(normalisePlate(raw));
console.log(isPlate('KJA-234-XY')); // true
console.log(isPlate('kja 234 xy')); // true
console.log(isPlate('kja234xy')); // true
Clean, then test. One line covers every way of typing the separators.
Step 4: the zero that looks like an O
const PLATE = /^[A-Z]{3}[0-9]{3}[A-Z]{2}$/;
const normalisePlate = (raw) => String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '');
const isPlate = (raw) => PLATE.test(normalisePlate(raw));
console.log(isPlate('KJ0-234-XY')); // false
The third character there is the digit zero, not the letter O. The pattern is right to reject it: that slot must be a letter. But in many fonts 0 and O look the same, so the person typing it can't see what's wrong. A message that just says "invalid plate number" won't help them. A better form says which part is wrong, for example "the first three characters must be letters".
Step 5: format it
const PLATE = /^[A-Z]{3}[0-9]{3}[A-Z]{2}$/;
const normalisePlate = (raw) => String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '');
function formatPlate(raw) {
const p = normalisePlate(raw);
if (!PLATE.test(p)) return '';
return p.slice(0, 3) + '-' + p.slice(3, 6) + '-' + p.slice(6);
}
console.log(formatPlate('kja234xy')); // KJA-234-XY
console.log(formatPlate(formatPlate('kja234xy'))); // KJA-234-XY
console.log(formatPlate('KJA-23-XY') === ''); // true
Three slice calls cut the cleaned text into its letters, digits and letters, with hyphens between. Formatting a plate that's already formatted changes nothing, because the hyphens are stripped again first.
An invalid plate gives '' instead of a half-formatted string like KJA-23X-Y. An empty result is easy to spot, while a wrong-looking plate might get saved.
Like any pattern, this only checks shape. AAA-111-AA is perfectly formed and may belong to no vehicle at all.
The full solution
The answer panel has all three functions and prints a small table of inputs. Its checks cover the standard form, lowercase with spaces, no separators, formatting twice, too few digits, digits in letter slots, the zero for O, and empty results for invalid input. Press Run to see the output.
const PLATE = /^[A-Z]{3}[0-9]{3}[A-Z]{2}$/;
const normalisePlate = (raw) => String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '');
const isPlate = (raw) => PLATE.test(normalisePlate(raw));
function formatPlate(raw) {
const p = normalisePlate(raw);
if (!PLATE.test(p)) return '';
return p.slice(0, 3) + '-' + p.slice(3, 6) + '-' + p.slice(6);
}
for (const p of ['KJA-234-XY', 'kja 234 xy', 'KJ0-234-XY', 'KJA-23-XY']) {
console.log(String(p).padEnd(12), isPlate(p), formatPlate(p));
}
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('the canonical form is accepted', isPlate('KJA-234-XY'), true);
test('so is lowercase with spaces instead of hyphens', isPlate('kja 234 xy'), true);
test('and with no separators at all', isPlate('kja234xy'), true);
test('all three print the same way', formatPlate('kja234xy'), 'KJA-234-XY');
test('formatting an already formatted plate changes nothing', formatPlate(formatPlate('kja234xy')), 'KJA-234-XY');
test('two digits where three belong is refused', isPlate('KJA-23-XY'), false);
test('so are digits in the letter slots', isPlate('123-KJA-XY'), false);
test('a zero typed for the letter O fails, and looks identical on screen', isPlate('KJ0-234-XY'), false);
test('an invalid plate formats to empty rather than to nonsense', [formatPlate(''), formatPlate('KJA-23-XY')], ['', '']);
The KJ0 case is the one worth remembering. A zero in a letter slot fails the pattern, which is correct, but the person who typed it cannot see the difference between 0 and O in most fonts — so "invalid plate number" is a useless message. Either say which slot is wrong, or fix the obvious confusions before validating (O to 0 in digit slots and back in letter slots) and tell the user what you assumed.
Stripping non-alphanumerics before matching means one pattern covers every way a human might type separators, and it makes the validator and the formatter share a single definition — worth doing because the two drifting apart is how a value passes validation and then displays wrongly. Returning '' rather than a half-formatted string for invalid input keeps the failure visible. As in exercise 114, shape is all this proves: AAA-111-AA is well formed and hanging on no vehicle.
Common mistakes
- Removing characters before uppercasing.
[^A-Z0-9]would delete every lowercase letter. - Leaving out
^and$. ThenXKJA234XYZcontains a match and passes. - Formatting invalid input anyway. Return
''so the problem can't be missed.
Try it yourself
- Write
plateProblem(raw)that returns'letters','digits'or''to say which part of the plate is wrong. - Before validating, replace
Owith0in the digit slots only, so'KJA-2O4-XY'is accepted asKJA-204-XY. - Write
samePlate(a, b)that returnstruefor'kja 234 xy'and'KJA-234-XY'.