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 moduleconst moment = require("moment")// create some dates and timeconst date1 = moment(); // current date and timeconst 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 timeconst 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 validconsole.log(date1.isValid()) // trueconsole.log(date2.isValid()) // trueconsole.log(date3.isValid()) // falseconsole.log(date4.isValid()) // trueconsole.log(date5.isValid()) // falseconsole.log(time1.isValid()) // falseconsole.log(time2.isValid()) // true
Code explanation:
- Line 2: We require the
momentpackage. - 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.