Validation of Dates

Having trouble with a JavaScript function I wrote to validate a date selected from a calendar against the current date. The date format being displayed in the text box is "01-Oct-2010". Here's the function I created:

function CheckDate() {
    var today = new Date();
    var startDate = document.getElementById("<%=txtStartDate.ClientID %>").value;
    var endDate = document.getElementById("<%=txtEndDate.ClientID %>").value;

    if (Date.parse(endDate) >= today) {
        alert("End Date should not be greater than Today");
    }

    return true;
}

Answer №1

let currentDate = new Date();
let dobValue = document.getElementById('dateOfBirth').value.split('-');
let birthDate = dobValue[0];
let birthMonth = getMonthInNumber(dobValue[1]);
let birthYear = dobValue[2];
let today = new Date();
currentDate.setFullYear(birthYear, birthMonth, birthDate);
let difference = (today.getTime() - currentDate.getTime());

if (difference < 0) {
    alert("Birth Date cannot be in the future");
}

You have permission to utilize the provided JavaScript code.

Note: Implement a function called getMonthInNumber that converts month values to digits as needed.

Answer №2

  1. eliminate hyphens
  2. validate against today.getTime() as Date.parse gives a timestamp, not a date object

simply modify

if (Date.parse(endDate) >= today) {

to

if (Date.parse(endDate.replace(/-/g," ")) >= today.getTime()) {

You might need to STANDARDIZE the date since the timestamp may be slightly different than when the date was created:

var endTime = new Date(Date.parse(endDate.replace(/-/g," ")).setHours(0,0,0,0).getTime();
var today = new Date().setHours(0,0,0,0).getTime();
if (endTime > today) {

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

Unable to include Electron in a React component for ipcRenderer

I've been attempting to import the ipcRenderer into a react component in order to communicate with the electron side. However, I'm facing issues trying to import electron. Here are some of the attempts I've made: import { ipcRenderer } from ...

Pass the response from a JavaScript confirm dialog to a Ruby program

Apologies if this question seems naive, but I am curious if it is feasible to pass the response from a JavaScript confirm box or message box as a value to a Ruby program. If I were to click on the "yes" button in the confirm box, could this response be st ...

Tips on adding up the values of fields in arrays in mongoose

const PostSchema = new mongoose.Schema({ title: { type: String, }, text: { type: String, required: true, } postedBy: { type: mongoose.Schema.ObjectId, ref: "User", } likes: [{ type: mongoose.Schema.ObjectId, ref: " ...

Convert a prototype code to jQuery using AJAX syntax

Seeking advice on my code syntax as I transition from Prototype to jQuery. I currently have both frameworks running simultaneously and aim to streamline all scripts into jQuery for improved page load efficiency and speed. Migrating from Prototype to jQue ...

ngSelect fails to load ajax data automatically upon page initialization

In my angular web application, I have a select element that is populated with data from an AJAX call. The issue I am facing is that the options in the select are not displayed until the select box is clicked on and then unfocused. Only after this action, a ...

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

Exploring the Depths of Web Scraping: A Guide to Scraping Within a Scraped Website

I have successfully scraped data from a specific page, but now I need to follow another href link in order to gather more information for that particular item. The problem is, I am unsure of how to do this. Here is an excerpt of what I have accomplished s ...

Transform the display format of the input type date field from 'MM/DD/YYYY' to 'February 5, 2012' in a React.js application using Material-UI's TextField component

https://i.stack.imgur.com/9p7Mz.jpg I am working with a material-ui/ TextField date component and I am looking to maintain the current style and input method, but I need to adjust how the entered value is displayed to the 'en-us' format. const o ...

Bootstrap: Display a single product on the Carousel Product Slider for the smallest view

I found an example I'm using at this link: I noticed that when I resize my BrowserWindow, the boxes start to shrink. However, when the width reaches about 990px, the single products are rearranged in a 4-block layout from the initial width. Is there ...

Enhance the image with interactive shapes using JavaScript or JQuery

Looking to integrate dynamic shapes such as circles, rectangles, lines, ovals, etc. into images using a jQuery plugin or JavaScript. For example: https://i.sstatic.net/zXWCF.png Similar to how dynamic text can be added by typing in a textbox, I am lookin ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

Issue with ng-pattern directive not working as expected within AngularJS

<label for="updateInterval" class="control-label" for="UpdateInterval">Choose Interval</label> <input name="intervalRange" id="intervalRange" ng-pattern="" type="number" class="form-control input-medium fld-updateinterval-val" placehold ...

Disable the ability to select text when double-clicking

Is there a way to prevent text selection on double click while still allowing selection on mouse drag? Whenever I try to remove selection on dblclick or mouseup, it flashes, which is not the desired outcome as shown in this jsfiddle. UPD: I am not lookin ...

The Javascript code is not running due to the XSS security measures in place

Within my Wordpress website, I have crafted an HTML form that enables users to view database records corresponding to their input. Following this AJAX tutorial on w3schools, a JavaScript function was implemented to send a GET request to a PHP script on the ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Issues with Cookies Updating Automatically - Using AngularJS

I have defined cookies using the following code snippet: $cookies.userName = $scope.userName; ($scope.username represents a variable) $scope.userName = $cookies.userName; When rendering it in HTML, I use the following code: {{userName}} The cookies val ...

What are some ways I can personalize my react-table components?

I want to customize the functionalities with unique layouts and positioning. Instead of using the default next and previous buttons, I prefer creating my own. Is there a way to achieve this without directly modifying the code in node_modules directory? ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

The plus sign ('+') fails to be matched by the regular expression in Angular 2, although it functions correctly in other testing environments

Check out this code snippet: export const PASSWORD_PATTERN: RegExp = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9`~!@#$%^&*()\-_+={[}\]|\\:;"'<,>.?/]{8,}$/; This constant is utilized in the following manner elsewhere: ...

What can I do to resolve the issue of my Navigation Bar being blocked by a Javascript map?

My navbar creates a dropdown menu when I hover over it, but the map generated with the script tag blocks it. Here is the current setup: // JavaScript Document //This will make the navigation bar responsive. function myFunction() { var x = document.ge ...