How to customise the "invalid date" in moment.js?

by filiberto , in category: Javascript , a year ago

How to customise the "invalid date" in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a year ago

@filiberto 

Moment.js does not provide a built-in way to customize the "invalid date" message.


However, you can create a custom function to handle invalid dates and display a custom message. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
moment.createFromInputFallback = (config) => {
  const invalidDateMessage = "This is not a valid date!";
  throw new Error(invalidDateMessage);
}

try {
  const date = moment("not a valid date");
} catch (error) {
  if (error.message === invalidDateMessage) {
    console.log("Custom invalid date message:", error.message);
  } else {
    console.error(error.message);
  }
}


In this example, we create a custom function createFromInputFallback that throws an Error with a custom message when an invalid date is passed to moment(). We then catch the error and check if it matches our custom message, and display it accordingly.


You can adjust the custom error message to your liking and modify the handling of the error as needed.

Related Threads:

How to handle invalid date in oracle sql?
How to parse date string with '0' day to date in moment.js?
How to convert new date() to utc date using moment.js?
How to compare moment.js date?
How to add and format date in moment.js?
How to change the date using moment.js?