Challenge with validating custom start and end dates in Angular Material datepicker

I am dealing with two dates, namely an arrival date and an exit date. I am attempting to implement custom validation where the exit date cannot be earlier than the arrival date. If it is earlier, then display an error message. Please refer to the code snippet below.

component.ts file:

  arrivalDate: ['', [Validators.required, this.validateArrivalDate()]],
      exitDate: ['', [Validators.required, this.validateExitDate()]],

 validateExitDate(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (this.currentTravelFormGroup !== undefined) {
        const exitDate = this.currentTravelFormGroup.controls['exitDate'].value;
        const arrivalDate = this.currentTravelFormGroup.controls['arrivalDate'].value
        if (exitDate <= arrivalDate) return { requiredToDate: true };
      }
    };
  }

  validateArrivalDate(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (this.currentTravelFormGroup !== undefined) {
        const exitDate = this.currentTravelFormGroup.controls['exitDate'].value;
        const fexitDate = new Date(exitDate);
        const arrivalDate = this.currentTravelFormGroup.controls['arrivalDate'].value;
        if (fexitDate <= arrivalDate) return { requiredFromDate: true };
      }
    };
  }

I have set up error messages in HTML as follows:

<mat-error *ngIf="currentTravelFormGroup.get('arrivalDate').hasError('requiredFromDate')">Please provide a valid arrival date</mat-error>   
<input class="form-control bgColor" [matDatepicker]="pickerExitDateFromGermany" placeholder="MM/DD/YYYY" [min]="minStartDateFutureTravel"  [max]="maxStartDateFutureTravel" formControlName="exitDate" id="exitDate" readonly (click)="pickerExitDateFromGermany.open()"
[ngClass]="{ 'is-invalid': submitted && travelDet.exitDate.errors }">
<mat-datepicker #pickerExitDateFromGermany></mat-datepicker>
<mat-error *ngIf="currentTravelFormGroup.get('exitDate').hasError('requiredToDate')">Please provide a valid exitdate</mat-error>

The current functionality correctly displays error messages for the exit and arrival dates. However, when the arrival date is set to 11/11/2019 and the exit date is set to 10/11/2019 (an error message is displayed below the exit input field). If I change the arrival date to 08/11/2019...

If you spot any issues or have suggestions on how to solve them, please feel free to share your insights. Thank you!

Answer №1

To address this issue, I successfully resolved it by making sure to clear, set, and update values following the validation checks in both the validateExitDate() and validateArrivalDate() methods.

validateExitDate(): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } | null => {
          if (this.currentTravelFormGroup !== undefined) {
            //const arrivalDate = control.value;
            const exitDate = this.currentTravelFormGroup.controls['exitDate'].value;
            const arrivalDate = this.currentTravelFormGroup.controls['arrivalDate'].value
            if (exitDate <= arrivalDate) return { requiredToDate: true };
            else{
                 this.currentTravelFormGroup.get('exitDate ').clearValidators();

               this.currentTravelFormGroup.get('exitDate').updateValueAndValidity();
            }
          }
        };
      }

The same steps were taken for the Arrivaldate function as well.:)

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

Utilizing ng-class to manipulate arrays in AngularJS

Within my controller's $scope, there is an array called myElements... $scope.myElements = [false, false, true, false, true, false]; ...and I want to assign the class firstClass to a div element if any of the elements in the array are true, otherwise ...

Swapping out an entire item in a designated array index for a different object

I am faced with a JavaScript object conundrum: const myValidation = [ { id:'1', name:'qqq', field1: 'Yes', field2: 'No', field3: 'Yes' }, { id:'330', name:'www', ...

When comparing dates in MongoDB between the frontend and backend, there is an exact match; however, the comparison still triggers

I offer a service that verifies if the date on the frontend matches exactly with the record in the backend database Here is the code snippet: if (schedule.due_date != paymentBody.user_view_before_schedule[i].due_date) { console.log(schedule.du ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

Employing jQuery tabs to reveal or conceal extra information

We have implemented a feature on our page where five tabs are used in the center column to show/hide content. Within the right-hand column, there is specific content that should only be visible when tab one (named '#overview') is selected, which ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Is there a way for me to have a table automatically scrolled to a specific column upon loading the HTML page?

My table contains a dynamic number of columns based on the months inputted from the database starting from a start_date and ending at an end_date. I have the current_date stored as a variable and want the table to load with the x-scrollbar positioned right ...

Using PHP to Generate Validation Rules for jQuery

I have been exploring the jQuery Validation plugin and came across the use of a callback to send additional data, such as a username, as mentioned in the official documentation. var myObj={ rules: { email: { required: true, ...

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

What is the best way to locate a table of a specific class using jQuery selectors?

Is there a way to specifically target a table with the class "d" using jQuery selectors? I'm having trouble making it work... var dTableTags = $(".d table"); For instance, an example table would look like this... <table id="thetable" class="d"&g ...

What solutions are available to resolve the routing problem in React.js?

On my fourth day working with Node and React.js, I am creating a custom offline search function for Docusaurus 2. I've built a JSON index and implemented a search function using elasticlunr. My goal is to redirect to a separate results page, but I&apo ...

Having trouble with utilizing react-select and its menuIsOpen attribute?

Currently, I'm navigating a complex component that requires the use of an options list. As react-select is already implemented throughout my application, it seems logical to utilize it in this scenario as well. My goal is to integrate react-select inl ...

Automatically sync textbox width with gridview dimensions

My goal is to dynamically resize a number of textboxes so that they match the width of my gridview's table headers. The gridview will always have the same number of columns, but their widths may vary. However, as shown in the image below, the width va ...

Send data using Javascript without having to refresh the page

As I work on submitting a form in JavaScript, the AJAX feature is functioning perfectly when manually submitting the form. However, there seems to be an issue when JavaScript attempts to submit it, resulting in a refresh. The current code snippet I am wor ...

The phenomenon of an invisible Absolute or relative position leading to grid components overlapping in Next.js

I've been struggling with this issue for over 48 hours now. I've attempted to troubleshoot by commenting out everything except the affected components and even swapping entire components around, but the problem persists. Oddly enough, rearranging ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

Unable to establish a connection with the browser using Socket.IO Spring server, but it works successfully when connecting with

After developing a Spring Boot Application with a SocketIoServer Endpoint, I encountered an issue where the server worked perfectly when tested in a Node.js client environment, but did not respond in Chrome or Edge browsers (haven't tested others). T ...

Display additional inputs using the PHP Foreach Loop depending on the selection made

I have a PHP Foreach loop that includes a "Quantity" input field. When users select a quantity, the corresponding number of new inputs should be displayed. For example, if the user chooses a quantity of "3", then 3 new inputs should appear for that item. K ...

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

What is the best way to store jQuery selections in a cache?

I have a need to cache approximately 100 different selections for animating. Provided below is sample code. Is there an issue with the syntax in the second example? If this isn't the correct way to cache selections, it's definitely the most popul ...