Skip to content

feat: add isDuration validator for ms-compatible duration strings#2674

Closed
Azarcodex wants to merge 1 commit intovalidatorjs:masterfrom
Azarcodex:feat/isDuration
Closed

feat: add isDuration validator for ms-compatible duration strings#2674
Azarcodex wants to merge 1 commit intovalidatorjs:masterfrom
Azarcodex:feat/isDuration

Conversation

@Azarcodex
Copy link

Summary

Closes #2668

Adds a new isDuration(str, options?) validator that checks whether a string
is a valid duration in the format used by the popular
ms package.

This was originally implemented in typestack/class-validator
(issue,
PR), where maintainers
recommended it belong here in validator.js instead.


What isDuration validates

It accepts duration strings matching the ms package StringValue format:

Format Example
Bare number (implicit ms) '100', '3.5'
Number + short unit (no space) '10s', '2m', '1h', '7d'
Number + short unit (with space) '10 ms', '2 h', '5 w'
Number + long unit '2 minutes', '3 hours', '4 days'
Decimal values '1.5h', '0.5 days', '2.75 weeks'
Case-insensitive '2 Days', '5 HOURS', '10MS'

Supported unit aliases

Unit Accepted values
Years years, year, yrs, yr, y
Months months, month, mo
Weeks weeks, week, w
Days days, day, d
Hours hours, hour, hrs, hr, h
Minutes minutes, minute, mins, min, m
Seconds seconds, second, secs, sec, s
Milliseconds milliseconds, millisecond, msecs, msec, ms

Options

Option Type Default Description
allowNegative boolean true Whether negative durations like '-1h' are considered valid

Usage

// Valid
validator.isDuration('10s')                            // true
validator.isDuration('2 days')                         // true
validator.isDuration('1.5h')                           // true
validator.isDuration('100 milliseconds')               // true
validator.isDuration('100')                            // true (bare number = ms)
validator.isDuration('5 HOURS')                        // true (case-insensitive)

// Invalid
validator.isDuration('')                               // false
validator.isDuration('abc')                            // false
validator.isDuration('10xyz')                          // false (unknown unit)
validator.isDuration('1h 30m')                         // false (compound not supported)

// With options
validator.isDuration('-1s')                            // true  (default)
validator.isDuration('-1s', { allowNegative: false })  // false


## Tests

-  4 new test cases added in [test/validators/isDuration.test.js](cci:7://file:///c:/Users/vpaza/dev/validator.js/test/validators/isDuration.test.js:0:0-0:0)
-  All 321 tests passing (`npm test`)
-  Build and lint pass with 0 errors

const allowNegative =
typeof options.allowNegative === 'boolean' ? options.allowNegative : true;

const match = msFormatRegex.exec(str);

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
library input
may run slow on strings with many repetitions of '0'.
@codecov
Copy link

codecov bot commented Mar 3, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (f39bb3b) to head (839c8a2).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #2674   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          114       115    +1     
  Lines         2592      2603   +11     
  Branches       660       665    +5     
=========================================
+ Hits          2592      2603   +11     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@WikiRik
Copy link
Member

WikiRik commented Mar 3, 2026

The person that created the issue, also created a PR for it; #2669 . Feel free to review that one, but since this is the duplicate I will be closing this one

@WikiRik WikiRik closed this Mar 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature: add validator for duration strings

2 participants