REGEXVAULTv2.0
Localization/Date Formats
Verified Safe

ISO 8601 Duration Regex for JavaScript

/^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching iso 8601 duration, ported and verified for JavaScript. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.

Javascript Implementation

Javascript
// ISO 8601 Duration
// ReDoS-safe | RegexVault — Localization > Date Formats

const iso8601DurationRegex = /^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;

function validateIso8601Duration(input: string): boolean {
  return iso8601DurationRegex.test(input);
}

// Example
console.log(validateIso8601Duration("P1Y")); // true

Test Cases

Matches (Valid)
Rejects (Invalid)
P1YP
P1Y2M3DPT
PT1H30M1Y
P1Y2M3DT4H5M6SP1YT
P30DP1Y2M3DT
PT0.5S
P1W

When to use this pattern

This pattern is drawn from the Localization > Date Formats category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

ISO 8601 specifies that W (weeks) cannot be combined with Y, M, or D components. This pattern allows the combination — enforce the restriction at application level if strict compliance is required.

Technical Notes

Lookahead (?!$) ensures at least one component is present. Capture groups: 1=years, 2=months, 3=weeks, 4=days, 5=hours, 6=minutes, 7=seconds. Weeks (W) cannot be combined with other date components in strict ISO 8601.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern