Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Regex for ISO 8601 durations

I need a regular expression to validate durations in the ISO 8601 duration format (with the exception of fractional parts which I don't need).

PnYnMnDTnHnMnS

PnW

Here is what I have:

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

The only problem is that the strings P and PT are allowed with this regex as all of the parts are "zero or one" ?.

  • There needs to be at least one component (date or time)
  • If there is a T then there needs to be a time component (H, M, or S)
  • If there is a T then there may or may not be any date components (Y, M, or D)
  • Overflow is allowed (e.g. P72H is mostly equivalent to P3D)

Acceptable inputs:

P1Y        // date component only
P2MT30M    // date and time components
PT6H       // time component only
P5W        // another date component

Unacceptable inputs:

P         // no components
PT        // no components
P3MT      // T specified but not time components

Right now the invalid strings are passing client-side validation but failing on the server-side because it's passed into DateInteval but I'd like to fail on the client side if possible. If everyone was using Chrome 40+ I could specify minlength='3' on the input element to help but that isn't the case unfortunately.

Answer*

Cancel
1
  • Please edit this to explain how it answers the question. I don't see anything that takes the input required by the question and I don't see any regex as wanted by the question. Commented Jan 29, 2025 at 13:03