Angular allows for a maximum time span of 60 days between two date inputs

I am looking to implement a validation in JavaScript or TypeScript for Angular where the start date cannot be more than 60 days after the end date is entered. The requirement is to enforce a "maximum range of 60 days" between the two input dates (dateFrom and dateTo). Hi there, I need help with JS or Angular TS to ensure that the start date is not more than 60 days after the end date is entered. The rule to follow is a "maximum range of 60 days" for the input dates.

datepicker(){
  var dateFrom = this.consultaForm.get('desdeCreacion').value;
  var dateTo = this.consultaForm.get('hastaCreacion').value;

  
  if(dateTo > (dateFrom < this.datePipe.transform(new Date(dateTo).getTime()-5100000000), 'yyyy-MM-dd')){
    alert('Rango máximo 60 dias');
    window.location.reload();}
  }

Answer №1

Personally, I believe there must be a more optimal solution, yet you can utilize the Date Object to manipulate the date accordingly.

updateDate(){
  var startDate = new Date(this.formData.get('startDate').value);
  var endDate = new Date(this.formData.get('endDate').value);

  
  if(endDate > new Date(startDate.setDate(startDate.getDate() + 60)) ){
    alert('Maximum range is 60 days');
    location.reload();}
  }

Answer №2

If you're looking to calculate the difference between two dates, you can create a utility function specifically for that purpose. Here's an example:

// Assuming fromDate and toDate are Date objects
// If not, you can convert them to Dates and pass them into this function
function findDateDifference(fromDate, toDate) {
  return Math.floor((toDate - fromDate)/(1000 * 60 * 60 * 24)) // Convert milliseconds to days
}

You can then incorporate this function into your validation logic, like this:

if(findDateDifference(startDate, endDate) <= 60) {
    alert('Maximum range is 60 days');
    window.location.reload();
}

Answer №3

Appreciate your help! I took your suggestions and implemented the solution as follows:

// Setting max range to 60 days (using sweetalert2)
var dateFrom60 = this.datePipe.transform(new Date(dateFrom).getTime()+5150000000,'yyyy-MM-dd');
if(dateTo > dateFrom60){
  this.hasta.reset();
  Swal.fire({
    icon: 'error',
    title: 'Maximum range exceeded: 60 days'
  })
}

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

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Transform the request in an Angular2 and jQuery Ajax POST call

I'm in the process of migrating my application from angularJS to angular2 and I've encountered a roadblock with an ajax POST call. return $.ajax({ url: "http://www.url.com", crossDomain: true, contentType: 'applicati ...

Issue with merging JSON in Angular using RxJS

Seeking assistance with combining two JSON objects in an Angular application. JSON Object 1: { "level1": { "level2": { "level31": "Text 1", "level32": "Text 2", "leve ...

Issue with DTO and a custom decorator in NestJS

I am currently facing an issue with using a DTO alongside a custom decorator within a NestJS controller for body validation. I am sending a request using multipart/form data, which requires me to parse the data from a string to JSON. However, when attempti ...

Can I use JavaScript to generate an element similar to <ion-icon name="heart"></ion-icon>?

Currently, I am utilizing a website called to incorporate icons into my buttons. It is quite straightforward with HTML when introducing a new element containing the icon. All you need to do is define a button and insert this code within it: ion-icon name= ...

When you click on a main category, a list of its corresponding subcategories will

concept image My vision involves having users click on a category from the top menu to display all main cards (parent cards), and then further clicking on a parent card will unveil its corresponding child cards. I've even included an image to help v ...

Troubleshooting Controller Action Failure in AJAX Request

Hello there I am encountering an issue with my AJAX call not reaching the Controller action in my ASP.NET MVC web application project. Below, you will find my AJAX call written in Javascript and the corresponding Controller's Action. Here is the AJA ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

HTML form with a dropdown menu

Imagine you have a HTML form containing two dropdown lists. The first dropdown is labeled "country" and contains a list of countries. The second dropdown, labeled "cities," should be dynamically populated based on the country selected. What is the best ...

Implementing a dynamic tab change functionality with props in Material UI tabs

Observing the following example: Link to Material UI Tabs Suppose I have these tab components within a widget, and I wish to include an image or icon. How can I link the icon or image so that when clicked, it changes to a specific tab without using react- ...

Using Angular for Sign in with Apple integration

I have been working on integrating Sign in with Apple into an Angular website. The implementation process begins with adding to the index.html file. Then I created a service named apple-login-service.ts using scriptjs. Here is the code for the apple but ...

Conditional Return Types in a Typescript Function

There is a function that can return two different types, as shown below: function doSomething(obj: {a: string, b?: string}): string | number { if (obj.b) { return 'something' } return 1 } When the function is called with an object cont ...

Load Ajax file smoothly without any flickering

I am working on a webpage that automatically loads data. The script I found on a tutorial website has a flaw - the text keeps blinking every few seconds. Is there a way to prevent this blinking effect? I am new to Ajax and finding it confusing. Below is t ...

Capture a fragment of a scene and convert it into a unique texture using THREE.JS

I'm interested in creating a texture of a specific area in my scene, similar to the example shown in the official documentation for three.js framebuffer here. As I examine the code provided, there's one particular aspect that's unclear to me ...

The website is having trouble reading the local json file accurately

Currently, I have developed an HTML site that utilizes JavaScript/jQuery to read a .json file and PHP to write to it. In addition, there is a C++ backend which also reads and writes to the same .json file. My goal is to transmit the selected button informa ...

Having trouble removing a DOM element with jQuery?

Hey there, I need your help with a jQuery issue I'm facing. I am currently working on cloning a div element that contains a span with a click event attached to it. The purpose of the click event is to remove the newly cloned section from the DOM. Whil ...

Creating dynamic form fields in Flask WTForm based on user's previous selection is a useful feature that can be achieved with some

I am interested in developing a form that dynamically generates different text area fields based on the selection made in a dropdown menu beforehand. Specifically, the idea is to create projects of various categories where, for instance, if a user chooses ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Refreshing HTTP request in Angular

I am currently working with Angular 5 and have encountered the following issue: Within my route, I have a parameter called year. The component related to this route is supposed to display data based on the year parameter, which is fetched from a service. ...

Attempting to assign a value to the Progress Circle

Can I modify the code to incorporate a hardcoded number instead of displaying "Goals completed:" and still have the progress bar reflect the percentage? I want to hide the prompt for users to input a number and handle all updates behind the scenes. Essent ...