Wednesday, 28 April 2021

Prevent moment.js accepting an integer as a valid ISO8601 date

I have some API's for creating dashboard widgets. Those API's return basic name/value data pairs that are passed to Google Charts. Moment.js checks whether the value is an ISO8601 date, and if so passes to Google Charts as a date instance.

However, the ISO_8601 isValid check is currently returning true if the date is a simple integer, e.g. 1234:

var myInt = 1234;
if (moment(myInt, moment.ISO_8601, true).isValid()) {
    console.log("Valid!");
}

I couldn't locate the necessary functionality to force a date format in the moment.js code, so this brutal hack works for now:

var myInt = 1234;
if (JSON.stringify(myInt).includes("T") && moment(myInt, moment.ISO_8601, true).isValid()) {
    console.log("Valid!");
}

Is there a correct way to use moment.js to configure the isValid() check?

The date format from my API is yyyy-mm-ddThh:mm:ss (without Z on the end).



from Prevent moment.js accepting an integer as a valid ISO8601 date

No comments:

Post a Comment