Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a variable is a Moment.js object?

My application has an HTML form with some inputs populated from the backend and other inputs being entered by the user (in a time input). An onChange function runs through each input when the user changes a value.

The inputs populated from the backend are converted to moment objects, the user-entered dates are mere strings. This means the onChange function encounters some moment objects, and some strings. I need to know which inputs are moment objects and which aren't.

What's the recommended method for testing if a variable is a moment object?

I've noticed moment objects have a _isAMomentObject property but I'm wondering if there's another way to test if a variable is a moment object.

Another option I've tried is calling moment on the variable regardless. This converts the string variables to moment objects and doesn't seem to effect existing moment objects.

like image 743
Brett DeWoody Avatar asked Apr 06 '16 16:04

Brett DeWoody


3 Answers

Moment has an isMoment method for just such a purpose. It is not particularly easy to find in the docs unless you know what to look for.

It first checks instanceof and then failing that (for instance in certain subclassing or cross-realm situations) it will test for the _isAMomentObject property.

like image 108
Jared Smith Avatar answered Oct 20 '22 09:10

Jared Smith


You can check if it is an instanceof moment:

moment() instanceof moment; // true
like image 43
Niels Heisterkamp Avatar answered Oct 20 '22 07:10

Niels Heisterkamp


moment() instanceof moment;

will always be true, because if you have

  • moment(undefined) instanceof moment
  • moment("hello") instanceof moment

you are always creating a moment object. So the only way is to check like this

  • moment(property).isValid()
like image 3
Fabien Sartori Avatar answered Oct 20 '22 08:10

Fabien Sartori