Open In App

Moment.js Parsing Validation

Date Validation in Moment.js moment#isValid is used to check whether a date is considered or not using Moment.js. This can be checked using moment#parsingFlags which returns an object in its response. Before proceeding, please install the moment.js library using the following command.

Moment.js moment#parsingFlags that results in an invalid date:



Installation:

npm install moment

Syntax:



moment(date: String).isValid()

Parameters: moment().isValid() does not accept parameters.

Return value: It returns a boolean value that tells whether a date is valid or not. 

Example 1: In this example, we will create an invalid date and check with moment#isValid.

Filename: main.js




const moment = require('moment');
let m = moment("2022-10-10T10:20:90");
console.log(m.isValid());

Step to run the application: Open the terminal and type the following command.

node main.js

Output:

false

Example 2: In this example, we will create a valid date and check with moment#isValid.

Filename: main.js




const moment = require('moment');
let m = moment("2022-10-10T10:20:50");
console.log(m.isValid()); 

Step to run the application: Open the terminal and type the following command.

node main.js

Output:

true

Reference: https://momentjs.com/docs/#/parsing/is-valid/

Article Tags :