How can we ensure that a date is in the future and formatted as dd/mm/yyyy using Javascript

I'm having trouble verifying the user input field to check if it is in the future and follows the dd/mm/yyyy format. The code I've written doesn't seem to execute the format validation part, and for some reason, nothing is working on Jsfiddle. However, the "check date in the future" function does work when tested locally.

I'm unsure about the correct approach to tackle this issue.

To illustrate, I've set up a demo on FIDDLE

Below is my complete javascript code. I prefer sticking with pure javascript:

function checkdate(){
    //var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
    var sendDate = document.getElementById('returning_date').value;

    sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
    today = new Date();
    today.setHours(0,0,0,0)
    
    if (sendDate < today) {
        //alert('The  date can\'t be in the past. Please pick another date.');
        document.getElementById('error8').innerHTML = 'The  date can\'t be in the past. Please pick another date.';
        return false;
    } else {
       document.getElementById('error8').innerHTML = '';
    }

    if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/)) {
      alert('works out');
    }
}

Could someone offer guidance on this problem?

Thank you in advance.

Answer №1

An issue arises when attempting to execute sendDate.match, as sendDate has been transformed into a Date object and therefore lacks a match method.

It is advisable to perform your regular expression check prior to converting it to a Date. In validation processes, it is common practice to ensure that the input adheres to a specific format before proceeding with additional validations such as range validation.

Answer №2

It is important to manually parse date strings instead of relying on the Date constructor or Date.parse for parsing (as they both function in the same way).

Validating and parsing a date string can be done by simply parsing the string and checking if it results in a valid date:

/* Parsing a string in d/m/y format. The separator can be any non-digit character.
** Ensures dates are not converted to the 20th century when dealing with two digit years
**
** @param {string} s - The date string to parse
** @returns {Date}
*/
function parseDMY(s) {
  var b = s.split(/\D/);
  var d = new Date();
  d.setHours(0,0,0,0);
  d.setFullYear(b[2], --b[1], b[0]);
  return d && d.getMonth() == b[1]? d : new Date(NaN);
}

// Testing a valid date
document.write(parseDMY('23/01/2016'));
// Testing an invalid date
document.write('<br>' + parseDMY('35/12/2016'));

Keep in mind that a date like 1/5/16 will be treated as 1 May, 0016. If you prefer day and month values to have two digits along with a four-digit year, you can add the following validation test at the end:

/^\d\d\D\d\d\D\d{4}$/.test(s)

However, enforcing two digits for day and month may not be practical since most people write dates without leading zeros such as "1/8/2016" instead of "01/08/2016".

Answer №3

To start, make sure to enclose the function within the <head> tags (click on the gear icon in the js tab) to ensure that the function can be located.

Your primary issue lies in the use of European date formatting, which will result in an "Invalid Date" error when attempting to create a date. Check out this helpful question for guidance on converting to USA-style and adapting it for compatibility with the Date object (see the reference page for more information on various applications).

Answer №4

Here is what I suggest:

Date.prototype.fromString = function(str) {
  var match = str.match(/([0-9]{2})(-|\/)([0-9]{2})(-|\/)([0-9]{4})/);
  if (match == null) {
    return null;
  }
  for (var index = 0; index < match.length; index++) {
    if (typeof(match[index]) === 'undefined') {
      return null;
    };
  };
  var year = parseInt(match[5]);
  var month = parseInt(match[1]) - 1;
  var day = parseInt(match[3]);
  if (month == 0 || day == 0) {
    return null;
  }
  return new Date(year, month, day);
}

function ensureValidDate(event, object, errorSelector){
  var inputDate = object.value;

  inputDate = (new Date()).fromString(inputDate);
  if (inputDate == null) {
    if (event.type == 'blur') {
      object.value = '';
    }
    return;
  }
  today = new Date();
  today.setHours(0,0,0,0)
  if (inputDate < today) {
    document.getElementById(errorSelector).innerHTML = 'The date cannot be in the past. Please choose another date.';
    return false;
  }
  else
  {
    document.getElementById(errorSelector).innerHTML = '';
  }
}        
$(function () {
});
<input onblur="ensureValideDate(event, this, 'error8');" onKeyUp="ensureValideDate(event, this, 'error8');" type='text' name="text1" placeholder='dd/mm/yyyy' id='returning_date'>
<span id='error8' style='color:red;'>format</span> <br><Br>

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

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

Determining the depth difference of nodes between two elements using JQuery

Is there a simple method to calculate the node depth difference between 2 elements? Example : <div id="1"> <div id="2"></div> <div id="3"> <div id="4"></div> </div> </div> <div id="5"></d ...

Troubleshooting AngularJS ng-route and Three.js crashes and glitches: A comprehensive guide

I am currently working on a website that utilizes angularjs along with the ng-route directive for navigation between different views. The site also incorporates Three.js for WebGL rendering on canvas. However, I am encountering difficulties as the applicat ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

What is the correct way to transform an Error object to a string in Node.js?

Every time I input a duplicate entry in mysql, this error pops up. { [Error: ER_DUP_ENTRY: Duplicate entry '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35465458455950755258545c591b-565a58">[email protected]< ...

Utilize Next.js to send an image to an email by leveraging the renderToString function on the API routes

I need help with sending styled emails that contain images. Currently, I am utilizing the renderToString method to pass props into my component. So far, everything is functioning correctly in the API routes. mport client from "@/lib/prisma"; im ...

onclick doesn't run the function

I have been encountering an issue with my HTML code that is supposed to clear web storage data upon clicking the "Clear Storage" button. Despite using this code snippet, the function to clear the storage does not seem to be triggering in Chrome and Firefo ...

Function on NextJS site failing to adhere to the two-second timeout limit

I have implemented an 'image slide show' that switches between images every two seconds by toggling their display types from "none" to "block". Within my .js file, the showSlides function is declared at the top: var slideIndex = 0; function sho ...

Is it possible to have a variable either inside quotation marks or NULL when checking for case within a string in JavaScript

The challenge lies in titling this particular question, but demonstrating it is quite straightforward. My goal is to include multiple value sets in an SQL insert statement like the following: var sqlInsertString = `INSERT INTO events (url) VALUES` var sqlI ...

Sliding in images with JQuery

I need help with animating the slide-in effect of 7 "card" images from the left to the center of the screen. I attempted to achieve this using the following code: function FetchCards() { $("#pack").css('margin-left', 0); $("#pack").css(& ...

The button will be disabled if any cells in the schedule are left unchecked

I am seeking help on how to dynamically disable the save button when all checkboxes are unchecked. Additionally, I need assistance with enabling the save button if at least one hour is selected in the schedule. Below is my code snippet for reference: htt ...

EJS files do not show variables passed from Node

I am currently developing a 'preferences' section on my website, where users can make changes to their email addresses and passwords. Within this preferences page, I aim to showcase the user's current email address. router.get("/settings", ...

Searching for date disparities in SQL - Oracle

I have a table: table-A id name dob city 1 John 05-08-1990 New York 2 Sarah 12-11-1985 Los Angeles 3 Mike 20-03-1979 Chicago 4 Emily 04-07-1995 Miami 6 Brian 15-09-1992 Seattle Date format ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

Passing JavaScript attribute events to alternative handler or type

As I set up a web page for a touch screen computer, I've come across an issue with triggering onclick events due to the size of my fingers causing the cursor to move as I attempt to click. To solve this problem, I am considering forwarding onmousedow ...

Preventing duplicate submissions ensures that submissions are sent only once

Encountered an issue with the multiple form page I'm working on: There are two forms present: <form> <input type="submit" id="single-submit" name="form_1" value="Submit 1"/> </form> <form> <input type="submit" id="single- ...

Mastering the use of node cluster mode in conjunction with agenda cronjobs

Currently, I am utilizing nodejs and agenda to run cronjobs. With a total of 10 cronjobs in place, the process is taking longer as nodejs is single-threaded and they all run simultaneously. In an attempt to resolve this issue, I experimented with pm2 by e ...

What are the common reasons for jQuery Image Slider malfunctioning?

After following a tutorial on Youtube (https://www.youtube.com/watch?v=KkzVFB3Ba_o) about creating a JQuery image gallery, I realized that my implementation is not working at all. Despite carefully reviewing my code and fixing any errors I could find, the ...

Exploring the intricacies of extracting nested JSON data in TypeScript

Can someone help me with this issue? https://example.com/2KFsR.png When I try to access addons, I only see [] but the web console indicates that addons are present. This is my JSON structure: https://example.com/5NGeD.png I attempted to use this code: ...

issue with angular and typescript

I'm currently working on developing an Angular 2 application that incorporates touch gestures using hammerjs. My goal is to merge the quickstarter application from: Angular 2 with the hammerjs application from: Hammerjs sample. However, I keep encou ...