schacki
schacki

Reputation: 9533

How to validate a moment.js duration?

It seems like only a moment() object has a isValid() method to check the validity of the provided data. Is there any equivalent for the moment.duration() object? Because isValid() does not seem to exist on durations.

Upvotes: 6

Views: 3132

Answers (3)

Coderer
Coderer

Reputation: 27274

I'm using Moment 2.29. It's easy to test for validity if your use case has a minimum valid length of the duration. For example, dur.isValid() && dur.as("minutes") >= 1 covers typographical errors, using NaN as numeric input, passing an invalid ISO8601 string, etc, because all those cases result in a zero-length duration. (If zero-length durations actually make sense for your use case, look to the other answers for guidance... but they probably don't.)

Upvotes: 0

fantom
fantom

Reputation: 555

In case of ISO8601 parsing, I suggest trying to parse it usign moment.duration(myIso8601Duration), get ISO8601 string from it again, using toISOString, and then compare it with myIso8601Duration. If they differs, input may be invalid.

Upvotes: 0

vicatcu
vicatcu

Reputation: 5837

I agree this seems to be an omission in moment. I have come up with the following workaround method of validating durations since I had the need. The insight is that an invalid duration, results an a duration that is exactly 'P0D'. Just sharing that here:

durationIsValid(iso8601DurationString){
  if(iso8601DurationString === 'P0D') return true;
  return moment.duration(iso8601DurationString).toISOString() !== 'P0D';
}

Hope this helps!

Upvotes: 2

Related Questions