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:
- overflow: It indicates a surge of a date field, for example, 30th February of the 13th Month.
- invalid month: It shows an invalid month name, such as January.
- empty: It means a string that is not parsable, for example, “this is a non-parsable string”.
- null input: It denotes a null input.
- invalid format: It denotes an empty list of formats passed to moment()
- userInvalidated: It denotes a date explicitly created as invalid.
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
Javascript
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
Javascript
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/