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

by filiberto , in category: Javascript , 9 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 9 months 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.