Validating dates in TypeScript

Currently, I am studying date handling and have an object that contains both a start and end date. For example: Startdate = "2019-12-05" and Enddate = "2020-05-20"

My goal is to establish a condition that first verifies the dates are not empty. After that, I want to ensure that the startdate remains unchanged or is updated to a date equal to today's date or later.

if ((startDate != null && endDate != null) && (????????????????)) {
    alert('Incorrect date');
     this.dateNotValid = false;
}

In place of the ??????? in the code snippet above, I wish to introduce a logic that enforces the startdate to remain either as "2019-12-05" or as today's date "2020-03-02" onwards. Any other date input should trigger an alert error message.

Answer №1

I'm a bit unclear on your instructions about checking for dates that are not empty, and ensuring that the start date matches the existing date or is a new date later than today's date.

If I were to make changes to the code, here's how I would do it:

let myInputDate = new Date('any-date-you-want')

let startDate = new Date('2019-12-05'); // example date
let endDate = new Date('2020-05-20'); // example date

if ((!!startDate && !!endDate) && ((myInputDate != startDate) && (myInputDate > endDate))) {
    alert('Incorrect date');
    this.dateNotValid = false;
}

Another suggestion from @Abhishek is to consider using the moment library, which can be very helpful when working with dates.

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

I'm curious about something I noticed in an HTML example within the text content section of elements. Can you help clarify this for me?

I recently came across a repository that was part of a bootcamp curriculum for learning full stack development. In one of the lessons on jQuery, students were tasked with building a calculator. However, I noticed some strange variables in the HTML where te ...

Tips on saving the background image URL value into a variable

How can I save the URL value of a background image in a variable? For example: image: url(images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg); I store this value as value = images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg in a variable and then use this variable in an href tag. ...

Iterate through the list of objects and display duplicates only once

var fixtures = [ { "matchday": 1, "homeTeamName": "Arsenal FC", "awayTeamName": "Leicester City FC" }, { "matchday": 1, "homeTeamName": "AFC Bournemouth", ...

Creating an async function in TypeScript to retrieve the coordinates of a particular location is a useful way to streamline the

I am looking to retrieve the coordinates of a location as the output of a function. The coordinates are already assigned within a fetch method, with latitudes stored as coordinates.lat and longitudes stored as coordinates.lng. [Currently, it is returning ...

Retrieving a collection of names from the properties of a specific type

Looking to replicate the properties and values of a custom type in an object: type MyType = { propA: string; propB: string; propC: string; } const obj = { propA: "propA", propB: "propB", propC: "propC", } A type ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

When the form is submitted, the text input vanishes and then the page is refreshed using AJAX technology

Can anyone help me troubleshoot why my page is reloading even though I used AJAX, and how to prevent it from clearing my input text after clicking the submit button? I tried using the show method to resolve this issue but it didn't work. <form met ...

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...

The special $ character in angularjs does not seem to be effective in filtering by object

Angularjs documentation states that the filter method should be able to accept an object as a parameter. This object allows you to specify the column to filter by, or use the special character "$" to search through all properties. While the filter works ...

What is the best way to automatically create a list of file names that can be used in a Grunt task?

I am currently utilizing load-grunt-config and grunt-prompt for my project development. I am working on an init task that involves moving php templates between folders. At the moment, I have hardcoded the template filenames, but I would prefer if Grunt co ...

Prevent Child Elements from Overstretching Container with Bootstrap Flex

I'm working on a layout where all elements can be viewed without the need for scrolling. Any panels that require more space should be scrollable. In the following example, I want the contents of main-left to be scrollable without stretching the entire ...

Text centered on hover for figure caption

Check out this fiddle http://jsfiddle.net/sLdhsbou/ where I am trying to center the "x" that appears on hover perfectly no matter what size the image is. Also, why does the transition not occur when moving the mouse outside of the figure, unlike when movi ...

Executing JavaScript with Python in Selenium

Completely new to Selenium. I need help running a javascript snippet in this code (as commented), but struggling to do so. from selenium import webdriver import selenium from selenium.common.exceptions import NoSuchElementException from selenium.webdriver ...

A Comprehensive Guide: Obtaining the Final Tab from a JSON using API

What is the method to extract the last tab from a given JSON code? { "claimed_levels": { "level_1", "level_2" } } I want to display the level when someone types "!levels". The desired output format should be: Your current level is "2" ...

Unraveling the intricacies of extracting data from nested object properties

Why do my variables stop being reactive after unwrapping from props? I have three components - a parent component, a second component for display, and a third component for updating data based on input (simplified code here). The third component updates ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Implement a counter in a JavaScript table, initializing it to zero

I have successfully written my code, but there is one issue. The first row is starting with the number one instead of zero. I'm looking for suggestions on how to start from zero. Any help would be greatly appreciated. Thanks! <script> var tabl ...

Troubleshooting: Why isn't setMetadata working in NestJS from authGuards

When I call my decorators, I want to set metadata for logging purposes. Within my controller, the following decorators are used: @Post("somePath") @Permission("somePermission") @UseGuards(JwtAuthGuard) @HttpCode(200) @Grafana( ...

JavaScript application that features an audio player complete with a dynamic progress bar and customizable tags

Looking to create a custom audio player using HTML, CSS, and JS. The player should have basic functionality like a play button and progress bar. However, I want to allow users to add tags on the progress bar of the audio file, similar to how SoundCloud&apo ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...