Checking the authenticity of Javascript Objects containing date values

What is the best way to validate a JavaScript Object that includes date fields?

While there are JSON validators such as tv4 that can check the format of string dates, our business logic operates with JavaScript Date instances which these validators do not support.

Our current validation process involves:

  1. Parsing the business object using JSON.parse() and a custom date reviver
  2. Executing business logic on the object, then performing validation
  3. Converting the object back to JSON using a date stringifier
  4. Re-parsing the string without the reviver
  5. Validating the final object

Is there a more efficient method to validate the business object directly without going through steps 3, 4, and 5?

For example:

The initial JSON string:

{
    "birth": "1994-03-17"
}

The schema for the JSON string:

{
    type: 'string',
    format: 'date-time'
}

The actual business object:

{
    birth: new Date("1994-03-17")
}

Answer №1

If you are utilizing the tv4 library, you can follow this approach:

tv4.addFormat('date-time', function (data) {
    if (data instaceof Date) return null;
    else return "not a valid date";
});

Your validation code should look like this:

{
    type: "object",
    format: "date-time"
}

This strategy is referenced in your inquiry (json schema date-time does not check correctly)

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

In TypeScript, fetch JSON data from a URL and gain access to an array of JSON objects

I'm struggling to find a solution and implement it in the correct format. An API returns a JSON file to me via a URL. The format is as follows: {"success":true, "data":[ { "loadTimestamp":"2022-07-20T ...

Exploring Angular 2 - examining how @input is implemented within the ngOnInit lifecycle hook for testing a component

Presently, I am facing a challenge while attempting to test a child component that is designed to receive input from the host component and utilizes the ngOnInit lifecycle hook as depicted in the following code snippet. @Component({ selector: 'my ...

What could be causing the custom aside or slide panel to not slide properly when using Angular Strap?

I recently tried creating a slide panel and came across the Angular Strap library. After studying the documentation, I attempted to implement the slide panel using this library. However, I encountered an issue where my side panel did not slide as demonst ...

The schema tag contains incorrect JSON syntax

Hey everyone, I'm completely new to Shopify and currently diving into the world of Liquid. I've encountered an issue with an invalid JSON tag in schema/ and I'm having trouble pinpointing its exact location. My goal is to create 4 basic bloc ...

Encountering an issue while trying to set up fs-ext with npm: error C3861: the 'fcntl' identifier cannot be

I encountered an error while trying to install fs-ext on my Windows 10 64-bit machine with Node.js v8.1.3 and npm v5.4.0. Any recommendations on how I can successfully complete the installation? PS C:\users\desktop\auth> npm install fs-e ...

Is it an issue with my code or Regex101? Diagnosing JavaScript/Node error

I'm currently working on an exercise assigned by my school which involves using regex. However, I'm facing some confusion regarding whether the issue lies in my function or in my regex code. Our instructor advised us to use regex101.com for testi ...

The JavaScript object is unable to reach the PHP controller

When I attempt to send a JavaScript Object to my PHP controller, it is arriving empty. Here is the object: https://i.sstatic.net/19gFV.png Upon arrival, the object appears empty. Here is my AJAX code: https://i.sstatic.net/ekHsC.png var SendMovs = { ...

Deploying a node add-on to a server bypassing the use of localhost

Currently, I have developed a node application that runs successfully on my local server. The project consists of an index.html file located in a public directory, along with the main app.js file. By executing the command node app.js in the terminal, the a ...

Steps for dynamically changing the class of a dropdown when an option is selected:

Check out this code snippet : <select class="dd-select" name="UM_Status_Engraving" id="UM_Status_Engraving" onchange="colourFunction(this)"> <option class="dd-select" value="SELECT">SELECT</option> <option class="dd-ok" value= ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

Personalized Design Incorporating Sections and Sidebars

I need the aside to be positioned on the right side and the section on the left side, both centered in the space. Feel free to check out this link <!DOCTYPE html> <html> <head> <style> #main { width: 800px; margin: 0 auto; } ...

MUI: Issue with pseudo element appearing cropped outside of Paper container

I am facing an issue where a red arrow pseudo element '::before' is partially cut off outside its container '.MuiPaper-root'. I need the arrow to remain visible, any suggestions on how to fix this? Here is the relevant code snippet and ...

The subsequent block within the code is being initiated following the initial block in Node.js

It was expected that "1" would be printed before "2", but the output is incorrect. fs.readdir("./my_stocks", (err, files) => { for(each in files){ var file=files[each]; if(file!='portfolio.js'){ var fn="./my_sto ...

Guide on how to programmatically assign a selected value to an answer using Inquirer

Currently, I'm utilizing inquirer to prompt a question to my users via the terminal: var inquirer = require('inquirer'); var question = { name: 'name', message: '', validation: function(){ ... } filter: function( ...

What is the process of creating a deep clone of the state and reverting back in Vuex?

Looking to create a snapshot or clone of an object property within the Vuex tree, make modifications, and have the option to revert back to the original snapshot. Context: In an application, users can test out changes before confirming them. Once confir ...

Instead of constantly updating my stateful component, I prefer to create a new paragraph for each new state

Each time the Create Sales Order Button is clicked, an API call is made and the response is printed as a Stateful Component. Rather than updating the existing component, I want to generate a new paragraph for each response received so that if the user clic ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON. However, when trying to close the new Promise function, I want the resolve function to return the ...

Troubleshooting: Height setting issue with Kendo UI Grid during editing using Jquery

Issue: My Kendo UI JQuery Grid is fully functional except for a bug that occurs when adding a new record. When I add and save a new record, the grid's footer "floats" halfway up the grid and the scrollbar disappears, making it look distorted. Furth ...