Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
schacki Avatar asked Nov 09 '22 11:11

schacki


1 Answers

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!

like image 71
vicatcu Avatar answered Dec 10 '22 19:12

vicatcu