What is moment().isValid() method in JavaScript?

Overview

In JavaScript, the moment.js package or module provides us the ability to manipulate dates and times easily. This package has an isValid method that allows us to check if a date or time is valid.

Syntax

moment(datetime).isValid
Check if a date or time is valid using moment.js

Parameters

  • datetime: This is a date or time that we want to check if it is valid.

Return value

This method returns a Boolean value. If the date or time provided is correct, then a true is returned. Otherwise, a false is returned.

Code example

Let's look at the code below:

// require the moment module
const moment = require("moment")
// create some dates and time
const date1 = moment(); // current date and time
const date2 = moment('2020.01.01', 'YYYY.MM.DD')
const date3 = moment([2010, 1, 14, 15, 25000, 5000, 125])
const date4 = moment(new Date) // current date and time
const date5 = moment([2015, 25, 35])
const time1 = moment(13187818764064345345)
const time2 = moment({hour: 20, minute: 20, second: 34})
// check if the dates and time are valid
console.log(date1.isValid()) // true
console.log(date2.isValid()) // true
console.log(date3.isValid()) // false
console.log(date4.isValid()) // true
console.log(date5.isValid()) // false
console.log(time1.isValid()) // false
console.log(time2.isValid()) // true

Code explanation:

  • Line 2: We require the moment package.
  • Lines 5 to 11: We create some dates and times. Some of them are valid, and some are invalid.
  • Lines 14 to 20: We use the isValid() method to check if the dates and times created are valid. Then we print the results to the console.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources