Open In App

Moment.js moment().invalid() Method

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The moment().invalid() method is used to return an invalid Moment object. This can be used in making our own parsers. The method accepts an object that can be used to specify the given parsingFlags in the object. We can specify any parsing flag, even if it is not recognized by Moment.

Syntax:

moment().invalid( Object );

Parameters: This method accepts a single parameter:

  • Object: This object is used to specify parsingFlags to the object. It is an optional parameter.

Return Value: This method returns an invalid Moment.js object.

Note: This will not work in the normal Node.js program because it requires an external moment.js library to be installed globally or in the project directory.

Moment.js can be installed using the following command:

Installation of moment module:

npm install moment

The below examples will demonstrate the Moment.js moment().invalid() Method.

Example 1:

Javascript




const moment = require('moment');
  
let invalidMoment = moment.invalid();
  
console.log(
    "Invalid Moment:", invalidMoment
)
console.log(
    "IsValid check:", invalidMoment.isValid()
);
console.log(
    "From Now of the Date:", invalidMoment.fromNow()
);
console.log(
    "Format of the Date:", invalidMoment.format()
);


Output:

Invalid Moment: Moment<Invalid date>
IsValid check: false
From Now of the Date: Invalid date
Format of the Date: Invalid date

Example 2:

Javascript




const moment = require('moment');
  
let invalidMoment2 = moment.invalid(
    
        invalidFormat: 'm:h',
        invalidMonth: "Decamber",
        someInvalidProperty: true
    }
);
  
console.log(
    "Invalid Moment:", invalidMoment2
)
console.log(
    "IsValid check:", invalidMoment2.isValid()
);
console.log(
    "Parsing Flags:", invalidMoment2.parsingFlags()
);


Output:

Invalid Moment: Moment<Invalid date>
IsValid check: false
Parsing Flags: {
  empty: false,
  unusedTokens: [],
  unusedInput: [],
  overflow: -2,
  charsLeftOver: 0,
  nullInput: false,
  invalidEra: null,
  invalidMonth: 'Decamper',
  invalidFormat: 'm:h',
  userInvalidated: false,
  iso: false,
  parsedDateParts: [],
  era: null,
  meridiem: null,
  rfc2822: false,
  weekdayMismatch: false,
  someInvalidProperty: true
}

Reference: https://momentjs.com/docs/#/utilities/invalid/



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads