User-generated JSON Object with Date Information

I have created an API using Node.js/Express that receives input from a form including a date option in the request body.

Currently, I am sending dates in the format YYYY-mm-dd, and I have also attempted using dd/mm/YYYY. However, when testing in Postman, the server crashes with the following 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 should be able to input dates in any desired format. How can I receive this input without encountering errors? Is there a correct approach to handling this issue? Thank you.

Answer №1

Hey there, I see you're working on a NodeJS/Express backend code. Let's consider a scenario where you have a POST route that receives a date input:

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

  // Extract the date submitted by the user from the request body
  var rawDate = req.body.date;

  // Create a new Date object from the extracted date string
  var dateObject = new Date(rawDate);

  // Validate the date object for correctness 
  //(check this helpful link: https://stackoverflow.com/questions/1353684/detecting-an-invalid-date-date-instance-in-javascript)
  // Perform necessary processing if the date is valid and send a response
  // Send an error response if the date is invalid

  ...

})

By passing the date string to Date(), it converts it into a manipulable Date object. Check out the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I utilized both of your mentioned formats to demonstrate an example in this terminal screenshot.

I hope this explanation is clear and beneficial for your project!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving JSON data following file read operation

I've been on a quest to find a way to read JSON files using JavaScript. The tutorial that came the closest to what I needed is located here: https://gist.github.com/zuch/6224600. cells.json: { "cells": [ { "img": "img/singlestitch_thumb. ...

Anticipate the middleware function to either invoke the next function or return a HTTP 400 status code

I am eager to delve into unit testing and am looking to test my Node API. I am utilizing Express with Typescript and Jest for testing. Prior to invoking the controller middleware, I apply the route input validation middleware to verify the validity of the ...

"Can you provide guidance on displaying a form for a specific element based on its unique ID

I am trying to display the edit form when clicking on a specific image, but it is currently showing for all tasks. I need help in figuring out how to make it show only for one task. I attempted to use useState to change the boolean value "active" to show ...

What is the best method for saving and accessing a user-entered date using session storage?

https://i.sstatic.net/I8t3k.png function saveDateOfBirth( dob ) { sessionStorage.dateOfBirth = dob; } function getDateOfBirth() { document.getElementById("confirm_dob").textContent = sessionStorage.dateOfBirth; } function pr ...

The Electron application is experiencing difficulties locating the module at /resources/app/index.js

Just started my journey with electron and successfully created my first electron application. It runs perfectly fine with npm start, but I encounter issues when trying to execute it with npm run. (I am using Ubuntu Linux). The command line interface displa ...

Determine whether a variable is defined following the keyup() event in jQuery

I am currently working on creating a registration form using the keyup() function in JQuery. For instance, when the input is correct, I assign it to a variable called txtuname. After pressing the register button, I need to ensure that all form variables ...

The function in Swift that allows for escaping

I recently tried following a tutorial on YouTube that demonstrated how to retrieve data from a JSON file. However, I found some of the steps confusing. Here's the specific function being used: func fetchJSONData (completion: @escaping () -> ()) { ...

What is the best way to locate all JSON key names?

Currently engaged in a machine learning project, I am in the process of identifying all the attributes within my dataset. The data is structured across multiple JSON files, each containing nodes with unique attributes. I am seeking an effective method to ...

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

Why is the home page on my jade website showing a blank screen?

Currently, I am following a tutorial on Express, Mongo, and Jade. While I have successfully retrieved data from MongoDB, Jade is not rendering my page correctly. Click here for the tutorial. Here are the snippets of code I am using: app.js: app.get(&apo ...

Retrieve the HTML tag content as a string using jQuery

For my OSINT project, I am developing a tool that needs to extract text from a specific HTML code string. $("p").text(); I'm looking for a way to make my variable work with the above code. Any suggestions? Share your ideas! Solution: $.ajax({ ...

What is the best method for resizing an SVG according to the size of my website's window?

I am attempting to implement a scalable settings icon SVG file that adjusts based on the window width. My approach involved creating a JavaScript function that alters the element's dimensions according to the window size, but unfortunately, this metho ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...

A stylish flyout menu with a sleek li background in jquery

Experimenting with http://tympanus.net/Tutorials/CufonizedFlyOutMenu/, I decided to remove the fly-in descriptions and am now attempting to load the extra li with a style that will "highlight" the li.current-menu-item element. An object is set up as follo ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

I need to update the class definition of a navigation menu item that contains an "a" tag with the class "section-link". How can I dynamically add the class "popover-link-a" to this definition using JavaScript?

If the grid in the body contains no data, then I want to display a pop-up message on the menu li element. This pop-up is triggered by adding the class popover-link-a. The current setup looks like this: <li id="tecrube" runat="server" ...

Increasing an element in an array of objects using MongoDB and Mongoose

In my possession is a document structured as follows: { "id": "12345", "channels": [ { "id": "67890", "count": 1 } ] } My objective is to increase the count of a specific channel by one. When a user sends a message, I must locat ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Using Mongoose schema object in Express 3 routes

How can I make MongooseSchema objects, defined in app.js, accessible to my routes? I encountered an error when attempting to use a variable set in app.js from routes/index.js. As a relatively new user of Node.js, I'm uncertain about what might be cau ...

Ways to include numerous RSS feeds

I'm having trouble figuring out how to include multiple RSS Feed URLs for parsing in my code. Currently, I can only parse one at a time. I attempted to use an array, but it's not functioning as expected. Any assistance would be greatly appreciate ...