JavaScript has a flaw in its date validation that allows for incorrect dates like 'dd.mm.0302' or '27.08.0974' to pass through

I have encountered an issue with date validation from the database where some years in the date fields appear to be incorrect (such as 28.02.0302). I need to validate these dates properly, but the functions I found online are not working as expected. How can I make them function correctly? Here are the functions I have attempted to use:

function isValidDate(d) {


if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());

}

function isValidDate11(s) {
    // format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

    if (dateFormat.test(s)) {
        // remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi,"$1");
        var dateArray = s.split(/[\.|\/|-]/);

        // correct month value
        dateArray[1] = dateArray[1]-1;

        // correct year value
        if (dateArray[2].length<4) {
            // correct year value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

Answer №1

Your script mistakenly changes the date you input as 28.02.0302 to the 28th of February in the year 2202, making it a valid date despite your intended date being different.

There are two specific parts of the script that cause this alteration:

The first part removes any leading zeroes from the date values, transforming the year from 0302 to 302.

// Remove any leading zeros from date values
   s = s.replace(/0*(\d*)/gi,"$1");

The second part checks if the date has less than 4 characters and adds 2000 if it's less than 50 and 1900 if it's more.

// Correct year value
if (dateArray[2].length<4) {
    dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}

The second part is slightly more complex, likely created to validate dates like 01.01.12 as 01/01/2012 and 01.01.93 as 01/01/1999.

These adjustments are not entirely necessary, and you can modify the function as follows:

function isValidDate11(s) {
    // Format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

    if (dateFormat.test(s)) {
        var dateArray = s.split(/[\.|\/|-]/);
        // Correct month value
        dateArray[1] = dateArray[1]-1;

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);

        if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
            return false;
        } else {
            return true;
       }
   } else {
        return false;
   }
}

Even though the date 28.02.0302 is considered valid due to being checked as the 28th of February in the year 302, it's important to define what you classify as a valid date.

If you encounter issues with dates like 0302, you may prefer a date format with a four-digit year and no leading zero:

function isValidDate11(s) {
    // Format D(D)/M(M)/YYYY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{4}$/;

    if (dateFormat.test(s)) {
        // Remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi,"$1");
        var dateArray = s.split(/[\.|\/|-]/);
        // Correct month value
        dateArray[1] = dateArray[1]-1;

        if(dateArray[2].length != 4){
          return false;
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);

        if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

This adjustment will resolve the issue with the 0302 year problem but may not work for dates ending with a two-digit year like .14.

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 the provided Javascript snippet, how would you classify `word` - a function, variable, or object?

Understanding that an object is a variable and a function is a type of object, I find myself confused about the proper way to reference word in the following code snippet: var word; exports.setWord = function(c, ch){ word = c.get('chats')[ch]; ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique. A typical fontObj consists of: { postscript: "Calibri", style: "Bold", family: "Calibri" } In my code, I aim to iterate ...

Node.js Middleware Design Pattern: Connectivity Approach

I am embarking on a journey to learn Javascript, Node.js, Connect, and Express as part of my exploration into modern web development stacks. With a background in low-level networking, diving into Node.js' net and http modules was a smooth process for ...

Sharing data between React JS components Passing information between different components in React JS

My NavBar.js component contains login information for the logged-in user. It displays "Welcome" along with the user details when the user is logged in. Now, I want to replicate this functionality in the ProductList.js component so that when a user posts a ...

Converting JSON into key-value pairs using ReactJS

Here is a JSON object that I have: [ { "crime": "LARCENY-NON_VEHICLE", "count": "23217" }, { "crime": "AUTO_THEFT", "count": "13675" ...

The API request for /api/auth/callback/credentials was resolved successfully, but no response was sent back. This could potentially lead to delays

When attempting to log in with Talend API Tester, I encountered the following message in the terminal: API resolved without sending a response for /api/auth/callback/credentials, this may result in stalled requests. Additionally, here is the screenshot ...

How do I show a panel within another panel in ExtJS without it showing a blank screen?

Ext.define('something', { extend: 'Ext.panel.Panel', layout: 'border', constructor: function(config){ let me = this; me.callParent(arguments); me.initConfig(config); } }); If I define a cl ...

Is there a method to stop react-select (Select.Async) from erasing the search input value when it loses focus?

Situation: In my setup, I have a standard select element (categories), which dictates the options displayed in a Select.Async component from react-select. Problem: Consider this scenario: a user is searching for an option within Select.Async whil ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

Tips for keeping a video background stationary while allowing the text to move smoothly

When I added the video for the background, it only appears at the top of the page. However, I want it to be visible as the rest of the page is scrolled. <div class="hero"> <video autoplay loop muted plays-inline class="back-video&qu ...

Transferring information from a server action to a server component

Is there a way to transfer data from my server action, specifically the value of the temperature variable, to the Home server component in my nextJS14 app? I want to display this value in the jsx of my Home server component. How can I achieve this? impor ...

I want to use React Bootstrap and Next.js to retrieve the text from a textbox in a React Component and then send it back to my Index.js file. How can I accomplish this task?

I need some assistance. Currently, I am facing a challenge. I am trying to retrieve data from one of my React Components named ParameterList. This component contains a React-Bootstrap Form.Control element for numerical input. My goal is to take the value ...

What steps can I take to address the issue of missing @angular/Core modules?

I am encountering an issue with running my Angular 2 project. Here's what I have tried: - Attempted to run the project using npm install and npm start, but it did not work - Cloned a quickstart from Github and replaced it with my src folder, only to ...

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Retrieving the attributes of a JSON object based on their names

I'm currently working on storing video information using JSON. I've managed to successfully read the JSON file, but I'm facing some challenges when trying to access the properties of the object. Specifically, I'm struggling with accessi ...

The use of '-' in v-bind:style within Vue.js

I'm having trouble figuring out how to use CSS code with dashes in v-bind:style. When I attempt something like this: <DIV style="width:100px;height: 100px;background-color: red;cursor: pointer;" v-bind:style="{ margin-left: margin + 'px' ...

Avoid receiving a 404 error when using an invalid ID

When trying to set up my workoutId param, I encounter the following error: UnhandledPromiseRejectionWarning: CastError: Casting to ObjectId failed for value "5fb02bd8b61abc02" at path "_id" for model "Workout" If the workou ...