Looking to modify your function to accept both current and future dates instead of just future dates?

I'm having trouble with ensuring that only today's date or a future date can be entered into my form. The function I'm using is supposed to accept the future dates, but for some reason, it's not working as expected. Can you help me figure out why?

//Here is the function that checks if the input date is either today or in the future

function isFutureDate(idate) {
    var today = new Date().getTime(),
        idate = idate.split("/");

    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
    return (idate - today) >= 0 ? true : false;
}

I also have another function that uses both RegEx and the above function:

function checkDate() {
    var redate = /((0)[1-9]|(1)[0-9]|(2)[0-9]|(3)[0-1])[\/](0[1-9]|1[012])[\/](20)(1)[4-7]/;
    var valid = true;
    var idate = document.getElementById("date");

    if (redate.test(idate.value)) {
        if (isFutureDate(idate.value)) {
            idate.style.border = "1px inset #EBE9ED";
            idate.style.borderRadius = "2px";
            document.getElementById("datewarn").style.display = "none";
        } else {
            idate.style.border = "1px solid red";
            idate.style.borderRadius = "2px";
            document.getElementById("datewarn").style.display = "none";
        }
    } else {
        idate.style.border = "1px solid red";
        document.getElementById("datewarn").innerHTML = "Enter a date in the format DD/MM/YYYY.";
        idate.title = "Please enter a date in the format DD/MM/YYYY.";
        document.getElementById("datewarn").style.display = "block";
        valid = false;
    }
}

Below is the HTML code snippet for the Date Input field:

<input type="text" id="date" placeholder="DD/MM/YYYY" onkeyup="checkDate()">

Answer №1

One approach could be to standardize the dates

function checkIfFutureDate(dateString) {
  var currentDate = new Date(), dateParts = dateString.split("/");
  currentDate.setHours(12,0,0,0); // or 0,0,0,0 based on personal preference
  var formattedDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0],12,0,0,0).getTime();

Answer №2

The reason for this is that the present time includes hours, minutes, seconds, and milliseconds, while the specified time in the string is calculated from midnight.

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

"Encountered a duplication issue while attempting to create a unique name by combining input from the textbox with the original file name using a combination of

Hey there, I'm looking to create a new name by adding the name from a text box to an original file. script.js angular.module('signin').service('fileUpload', ['$http', function ($http) { this.uploadFileToUrl = funct ...

When I use Input.value, it seems to cause a strange lag in my console.log

My goal is to have a text input on the page that triggers #fourChord's text to change as I type characters into the input. The issue I am facing is that console.log registers my input, but the first character is always ignored. For example, if I type ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Switching the color scheme between mobile and desktop devices to make the background look

As a newcomer to threejs, I have just begun learning and developing with this technology. I am aware that certain features may be different on mobile browsers compared to desktop ones due to limitations. However, I have encountered an issue that I cannot s ...

Tips for utilizing the .ready() function within the .load() method

With the implementation of a jQuery script on my website, I have created a dynamic platform where the main content changes as you navigate without fully reloading the page. However, there is an issue with the .load() function in jQuery that interferes with ...

The Angular framework's structure is loaded in a combination of synchronous and asynchronous ways once the primeng tableModule

Encountered this error while trying to load the TableModule from primeng into my components module file and running 'npm run packagr': Maximum call stack size exceeded To address this, I switched my primeng version from primeng12 to primeng11.4. ...

Creating a custom Chrome extension with the ability to modify the pop-up window instead of the web page

Is there a way to modify the content inside my extension's pop-up without affecting the web page being viewed by the user? Also, how can I ensure that my dropdown list functions correctly? I have two dropdown lists where selecting an option from the ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Utilize the `document.getElementById` method to trigger both function 2 and form 2 when clicked

Hey there, I'm having some issues with my code and would appreciate some help. After a user submits my form with the ID of 'fwrdform' using the onclick event, I want to also trigger another function from my 'logout-form' so that t ...

Developing a right triangular prism with Three.js

I am working on creating a right triangular prism. Here is the current code I have: var triangleGeometry = new THREE.Geometry(); triangleGeometry.vertices.push(new THREE.Vector3(-1.0, 1.5, 0.95)); triangleGeometry.vertices.push(new THREE.Vector3(-1.0, ...

Firebase Cross-Origin Resource Sharing (CORS) and IP range whit

Is there a way to whitelist two IP ranges in order to access my firebase cloud functions? I believe it should be possible to define them within this code snippet: const cors = require('cors')({ origin: true }); I tried searching on Google f ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

Check for input validation with jQuery when the element has a specific class

Utilizing the jQuery validation plugin for a checkout form on an ecommerce platform has proven to work excellently. However, I am in need of validating only those inputs that do not possess the class no-validate. Would it be possible to make use of the de ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

The setInterval function for the automated image slider is experiencing issues and is not functioning properly

I am facing an issue where the third photo in the slider does not appear initially. Eventually, the slide fails completely, causing the photos to change rapidly. Strangely, after the slide fails, the third photo sometimes appears sporadically. I am puzzl ...

Using a loop in JavaScript to validate credit card information by cycling through the form field names and identifying any errors

Embarking on a challenge for a course. Required to perform credit card validation according to these specific guidelines: You are establishing your own credit card company. You have devised a new method to validate credit cards using a straightforward fun ...

Creating a "save as" button in HTML - a step by step guide

When browsing the internet, if you want to save an HTML page you are viewing, you typically go to the File menu and select Save As. Is it possible to add a small button at the bottom of an HTML page that performs the same action? Instead of navigating thr ...