Dates, times and numbers

Intermediate · 9 min

Match ISO dates, 24-hour times, integers, decimals and scientific notation. Learn why a regex cannot know February 30th, and where locale formats break it.

Before thisCounted repetitionAlternationCharacter classesValidating input: emails, URLs and addresses

Leela Web Dev · 9 min

Dates, times and numbers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Leela Web DevReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A character class is a set of characters, not a numeric range. [0-12] means 0, 1 or 2. To match 0 to 12 you spell the number out: (?:0?\d|1[0-2]).
  • A tight ISO date pattern with month 01-12 and day 01-31 still accepts 2026-02-30 and 2026-04-31. Calendar rules need a date library, not a longer regex.
  • Do not trust new Date() alone either. new Date('2026-02-30') rolled over to 2 March. Parse, format back, and compare, or use Temporal.PlainDate.from, which threw.
  • Number patterns are choices about grammar: leading +, leading zeros, .5 and 5., exponents. JSON's grammar rejects +3, .5, 5. and 01, which Number() accepts.
  • Thousands separators are locale data. A US-style ^\d{1,3}(?:,\d{3})*$ rejects German, Indian and French formatting of the same number.

Shapes you can check, meanings you cannot

Dates and numbers look like perfect regex territory: a fixed layout, digits and punctuation. And the layout half is. What goes wrong is the other half. 2026-02-30 has the right layout and is not a day that ever existed. A regex sees characters. It has no calendar.

The range trap

The first mistake people make is writing a range of numbers like a range of characters. I tested /^[0-12]$/ against 12, 2 and 1: it rejected 12 and accepted 2 and 1. A class is a set of single characters. [0-12] is the characters 0, 1 and 2, with the 1 and 2 repeated. To match 0 to 12 you spell the number out as a choice of digit patterns:

(?:0?\d|1[0-2])

That is how every numeric range gets built: split it into groups that share a leading digit. It is exactly what the video below explains, with a generator for the tedious cases.

ISO dates, 24-hour times

For a date in YYYY-MM-DD form, a shape check and a range check:

shape   /^\d{4}-\d{2}-\d{2}$/
ranged  /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/

I ran both on Node 26 over 11 strings:

2026-11-23   shape true   ranged true
2026-13-45   shape true   ranged false
2026-00-10   shape true   ranged false
2026-02-30   shape true   ranged true    <- not a real date
2026-04-31   shape true   ranged true    <- not a real date
2025-02-29   shape true   ranged true    <- 2025 is not a leap year
2024-02-29   shape true   ranged true    <- leap year, valid

The ranged pattern catches month 13 and day 45 and lets 2026-02-30 through. Tying the day limit to the month and the leap-year rule is possible in principle with an enormous pattern, and nobody should maintain it. Split the work. Let the regex confirm the layout and capture the parts, then ask a date API whether the date exists.

new Date() is not that API on its own: new Date("2026-02-30") came back as 2 March, and new Date("2025-02-29") as 1 March. It rolls over instead of rejecting. Two options worked. A round trip: build the date, format it back, and compare to the input; that rejected every impossible date above. And Temporal.PlainDate.from("2026-02-30") threw RangeError: Parsed day value not in a valid range, while 2024-02-29 parsed. Temporal exists on Node 26 here, so check your own targets before depending on it. Python agrees: datetime.date.fromisoformat('2026-02-30') raised ValueError: day is out of range for month.

For a 24-hour time, ^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$ accepted 00:00, 23:59 and 23:59:59, and rejected 7:05, 12:60 and 23:59:60. It also rejected 24:00, which some ISO uses accept as “end of day”, and the leap second 23:59:60. These are choices; write them down.

Numbers are grammar choices

“A number” is several different grammars. Here are three, run against twenty inputs, next to JSON’s rule and the built-in Number():

input        int   dec   sci   json   Number()
"42"         yes   yes   yes   yes    42
"+3"         yes   yes   yes   no     3
".5"         no    yes   yes   no     0.5
"5."         no    yes   yes   no     5
"1e3"        no    no    yes   yes    1000
"01"         yes   yes   yes   no     1
"1,000"      no    no    no    no     NaN
"0x10"       no    no    no    no     16
""           no    no    no    no     0

The patterns are int = ^[+-]?\d+$, dec = ^[+-]?(?:\d+\.?\d*|\.\d+)$, sci = dec plus an optional (?:[eE][+-]?\d+)? before the $, and json = ^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$. They disagree on +3, .5, 5. and 01, and each disagreement is a product decision. JSON refuses a leading +, a bare .5 and leading zeros, and JSON.parse threw on all of them.

Number() is no substitute for stating the grammar. Number("") is 0, Number("0x10") is 16, and Number(" 12") is 12. A form that “validates with Number” accepts all three. A regex for the grammar you want, followed by Number to convert, is the usual combination.

Thousands separators are locale data

A US-style grouped number is ^\d{1,3}(?:,\d{3})*(?:\.\d+)?$. It accepted 1,234,567.89 and 0.5 and rejected 1,234,56. Then I formatted the same number, 1234567.891, in four locales:

en-US  "1,234,567.891"   matches
de-DE  "1.234.567,891"   no match
en-IN  "12,34,567.891"   no match
fr-FR  "1 234 567,891"   no match, the spaces are U+202F

Dots and commas swap roles, India groups in 2s after the first 3, and French uses a narrow no-break space that is not even a regular space character. A regex cannot guess which one a user typed. Decide the formats you accept, or parse with Intl.NumberFormat knowledge of the locale, and use the pattern only to check the shape. Inserting separators into a number is a different task, covered in combining lookarounds.

About the video

“34. Validating the Date Format using Regular Expression - RegEx” is from the Leela Web Dev channel, published 24 July 2022, 9 minutes 21 seconds. The description says only that it shows how to validate the date format with a regular expression. The chapters are “Introduction”, “Date Format” and “Date Validation”. I couldn’t read a transcript, so I can’t say which date formats it uses, whether it checks month lengths, or which language it runs in. It does not cover times, decimals, scientific notation or thousands separators, which come from my own runs. The numeric-range trap has its own short video in the deeper links, from Wiktor Stribiżew’s Regex Quickies series. English per its title and description.

What I did not run

Time-zone offsets in ISO timestamps, week dates, other calendars, currency formats, and parsing localised numbers back into values; I only ran Intl formatting. I did not generate the large ranges the video’s generator produces.

Next

Real data is rarely one clean field. Parsing log lines with named groups builds one pattern from a sample line.

Check yourself

  1. 01Why does /^[0-12]$/ not match the string 12?

    A class matches one character from a set, and [0-12] is the set {0, 1, 2}. It cannot match the two-character string 12. Write (?:0?\d|1[0-2]) for 0 to 12.

  2. 02A pattern with month (?:0[1-9]|1[0-2]) and day (?:0[1-9]|[12]\d|3[01]) accepts 2026-02-30. Why, and what do you do?

    The month and day are checked separately, and a regex has no way to tie the allowed day count to the month and the leap year. Check the shape with the regex, then validate the calendar with a date API, such as parsing and comparing the result.

  3. 03Why is 1,000 not matched by the decimal number pattern ^[+-]?(?:\d+\.?\d*|\.\d+)$?

    The pattern has no place for a comma. A number with grouping separators is a different grammar, such as ^\d{1,3}(?:,\d{3})*(?:\.\d+)?$, and a different locale uses different separators again.

  4. 04You validate numeric text with Number(input). Which two inputs fool it?

    The empty string gives 0 and '0x10' gives 16, so both look like valid numbers. ' 12' is accepted with its whitespace. A regex or a stricter parser makes the grammar explicit.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark