Parse and validate a dd/mm/yyyy date in JavaScript
Advanced · 4 min read
In Nigeria, the UK and much of the world, dates on forms are written day first: 15/01/2026 for 15 January 2026. JavaScript's own date parsing doesn't reliably understand that order. Hand it the text and you can get an invalid date, or, worse, a valid date with the day and month swapped.
In this tutorial you will write parseDMY(text), which reads a dd/mm/yyyy string and returns a real Date, or null for anything that isn't a real date: 31/02/2026, 15/01/26, the wrong separator, letters. You need to know strings, arrays and how new Date(year, month, day) works. Months count from 0, so January is 0.
Why not just use new Date(text)?
console.log(String(new Date('15/01/2026'))); // Invalid Date
console.log(new Date('03/04/2026').getMonth()); // 2, which is March
console.log(new Date('03/04/2026').getDate()); // 4
A string like 15/01/2026 isn't in a standard format, so how it's read is up to the JavaScript engine. Node.js rejects it. 03/04/2026 is worse: it's read month first, as 4 March, with no error at all. Someone who meant 3 April gets the wrong date and nobody is told.
So we'll take the string apart ourselves and build the date from its numbers.
Dates that don't exist roll over
new Date never checks the day. If you ask for 31 February, it counts on into March:
const d = new Date(2026, 1, 31);
console.log(d.getMonth(), d.getDate()); // 2 3: 3 March
That sounds like a problem, but we'll turn it into the check itself.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
132 Read a date the way a Nigerian form writes it
hardParse dd/mm/yyyy into a date, and reject anything that is not really a date: 31/02/2026, 15/01/26, letters, the wrong separator. Do not hand the string to new Date() and hope.
Stuck? Three hints, smallest first
- 1. Split on the slash and check you got three pieces of the right length, all digits.
- 2. Build the date, then read it back: a rolled-over date will not match what you asked for.
- 3. That round-trip is the only check you need for month lengths and leap years.
Step 1: split into three parts
console.log('15/01/2026'.split('/')); // [ '15', '01', '2026' ]
console.log('15-01-2026'.split('/')); // [ '15-01-2026' ]
console.log('1/2/3/4'.split('/').length); // 4
split('/') cuts the text at each slash. A real date gives exactly three pieces. The wrong separator gives one piece, and extra slashes give too many. So the first check is parts.length !== 3.
Step 2: check the shape of each part
The day and month can be one or two characters, and the year must be exactly four. Each part must be digits only.
Why not just use Number()? Because it's too forgiving:
console.log(Number(' 5')); // 5: the space is ignored
console.log(Number('1e1')); // 10: read as 1 times 10
console.log(Number('')); // 0
A small helper checks that every character is a digit:
const digitsOnly = (s) => s.length > 0 && [...s].every((c) => c >= '0' && c <= '9');
console.log(digitsOnly('2026')); // true
console.log(digitsOnly('oga')); // false
console.log(digitsOnly('')); // false
[...s] spreads the string into an array of characters, and every checks each one. Comparing c >= '0' && c <= '9' works because the digit characters sit next to each other in order.
Requiring four digits for the year means 15/01/26 is rejected. 26 could mean 2026, 1926, or the year 26. It's safer to ask the user again than to guess.
Step 3: build the date and read it back
Now we know we have three numbers. Build the date, then check that the day, month and year that come back are the ones that went in:
const digitsOnly = (s) => s.length > 0 && [...s].every((c) => c >= '0' && c <= '9');
const stamp = (d) =>
d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
function parseDMY(text) {
const parts = String(text).split('/');
if (parts.length !== 3) return null;
const [dd, mm, yyyy] = parts;
if (dd.length > 2 || mm.length > 2 || yyyy.length !== 4) return null;
if (!digitsOnly(dd) || !digitsOnly(mm) || !digitsOnly(yyyy)) return null;
const day = Number(dd);
const month = Number(mm);
const year = Number(yyyy);
const date = new Date(year, month - 1, day);
const same = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
return same ? date : null;
}
console.log(stamp(parseDMY('15/01/2026'))); // 2026-01-15
console.log(stamp(parseDMY('1/1/2026'))); // 2026-01-01
console.log(parseDMY('31/02/2026')); // null
console.log(stamp(parseDMY('29/02/2028'))); // 2028-02-29
console.log(parseDMY('29/02/2026')); // null
console.log(parseDMY('15/13/2026')); // null
console.log(parseDMY('15/01/26')); // null
month - 1 converts the human month (1 to 12) to JavaScript's (0 to 11).
This read-back is called a round trip, and it's the clever part. 31/02/2026 builds 3 March, whose day is 3, not 31, so it's rejected. Month 13 rolls into the next year, so the year doesn't match. 29 February passes in 2028, a leap year, and fails in 2026. We never wrote a table of month lengths or a leap-year rule: the round trip covers them all in three comparisons.
stamp just prints the result as yyyy-mm-dd so it's easy to read.
Step 4: one more trap with ISO strings
You might think the fix is to rewrite the date as 2026-01-15 and pass that to new Date. Be careful: a date-only string in that format is read as midnight UTC (the time at Greenwich), not your local midnight.
console.log(new Date('2026-01-15').toISOString()); // 2026-01-15T00:00:00.000Z
The Z means UTC. For anyone west of Greenwich, that moment is still 14 January locally. Building the date from its numbers, as parseDMY does, keeps it in local time and avoids the problem.
The full solution
The answer panel has digitsOnly, stamp and parseDMY, and prints the result for eight inputs, real dates and bad ones. Press Run to see the output.
const digitsOnly = (s) => s.length > 0 && [...s].every((c) => c >= '0' && c <= '9');
const stamp = (d) =>
d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
function parseDMY(text) {
const parts = String(text).split('/');
if (parts.length !== 3) return null;
const [dd, mm, yyyy] = parts;
if (dd.length > 2 || mm.length > 2 || yyyy.length !== 4) return null;
if (!digitsOnly(dd) || !digitsOnly(mm) || !digitsOnly(yyyy)) return null;
const day = Number(dd);
const month = Number(mm);
const year = Number(yyyy);
const date = new Date(year, month - 1, day);
// The round-trip. Date rolls impossible days forward, so if the parts that come
// back are not the parts that went in, the input was not a real date.
const same = date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
return same ? date : null;
}
const inputs = ['15/01/2026', '1/1/2026', '31/02/2026', '29/02/2028', '29/02/2026', '15/01/26', '15-01-2026', 'oga/01/2026'];
for (const text of inputs) {
const parsed = parseDMY(text);
console.log(text.padEnd(13), parsed ? stamp(parsed) : 'rejected');
}
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 well formed date parses', stamp(parseDMY('15/01/2026')), '2026-01-15');
test('single digit day and month are allowed', stamp(parseDMY('1/1/2026')), '2026-01-01');
test('29 February is real in 2028 and not in 2026', [stamp(parseDMY('29/02/2028')), parseDMY('29/02/2026')], ['2028-02-29', null]);
test('and this is what the round-trip is catching', new Date(2026, 1, 31).getDate(), 3);
test('a day that does not exist is rejected, not rolled', [parseDMY('31/02/2026'), parseDMY('32/01/2026'), parseDMY('15/13/2026')], [null, null, null]);
test('a two digit year is rejected rather than guessed', parseDMY('15/01/26'), null);
test('so are the wrong separator and letters', [parseDMY('15-01-2026'), parseDMY('oga/01/2026'), parseDMY('15/01/2026/9')], [null, null, null]);
test('the built-in parse of an unreadable string gives NaN, not null', Number.isNaN(new Date('oga').getTime()), true);
test('and a date-only ISO string is read as UTC, which is a different instant from local midnight', new Date('2026-01-15').toISOString(), '2026-01-15T00:00:00.000Z');
The round-trip is the whole technique. Rather than encoding month lengths and the leap-year rule, build the date and read it back: new Date(2026, 1, 31) comes back as 3 March, the day no longer matches the 31 that went in, so the input is rejected. Twelve month lengths, the four-hundred-year leap rule and every edge case collapse into three comparisons.
Everything else here is about refusing to guess. new Date('15/01/2026') is a non-standard format, so what it does is up to the engine; new Date('03/04/2026') is worse, because every engine reads it happily and reads it as the American month-first order, so the 3rd of April becomes the 4th of March with no error anywhere. A two-digit year is the same problem: 26 might be 2026, 1926, or the literal year 26, and the honest answer is to reject it and let the form ask again.
The last assertion is the one that catches people who did switch to ISO strings. '2026-01-15', date-only, is defined to be parsed as UTC, while '2026-01-15T00:00' is local — so in any timezone behind Greenwich the first one prints as the 14th. If a string carries no timezone, construct the date from its parts and keep the ambiguity out of the code.
Common mistakes
- Passing the text straight to
new Date(). Day-first strings are invalid or silently read as month first. - Trusting
Number()to check digits. It accepts spaces,1e1and the empty string. - Checking only that the numbers are in range. Day 31 is fine in January and not in February. Build the date and read it back.
Try it yourself
- Also accept
-and.as separators, as in15-01-2026and15.01.2026. - Write
formatDMY(date)that turns aDateback intodd/mm/yyyywith leading zeros. - Reject dates in the future, for a date-of-birth field. Pass "today" in as an argument.