0

I have an API with Nodejs/Express which receives input from a form with an option for date as request body.

I am currently sending this format of date YYYY-mm-dd and have also tried this one too dd/mm/YYYY but the server crashes when I test in Postman with this error:

UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: experience.0.from: Cast to Date failed for value "2017-14-09" at path
"from"
at new ValidationError (D:\ReactDev\MERN Dev\DevConnect\dev-connect\node_modules\mongoose\lib\error\validation.js:30:11)
at model.Document.invalidate (D:\ReactDev\MERN Dev\DevConnect\dev-connect\node_modules\mongoose\lib\document.js:1957:32)
at EmbeddedDocument.invalidate (D:\ReactDev\MERN Dev\DevConnect\dev-connect\node_modules\mongoose\lib\types\embedded.js:287:19)

The user ideally can input any format of date they desire but how do I receive the input without errors. Is there a proper way to do this? Thanks.

Darth Plagueris
  • 339
  • 4
  • 20

1 Answers1

0

ok, not sure what's your backend NodeJS/Express code, but let's say you have a POST route like this that receives a date:

app.post('/', function (req, res) {

  //extract the user submitted date from the request body
  var rawdate = req.body.date

  //create a new Date object
  var date = new Date(rawdate)

  //check that the date object is valid (here a helpful link: https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript)
  //if the date is valid, do your processing then send a response
  //if the date is not valid, send an error http response back to the user

  ...

})

so basically by passing it to Date() you turn any date string into a Date object, that you can manipulate however you want. Here a reference to the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I tried using both of your formats to show you an example: terminal screenshot

Hope it helps!

bitfede
  • 31
  • 5
  • 1
    "*…by passing it to Date()*". Please take note of the linked article: "*parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.*" – RobG Oct 04 '18 at 09:10