How to implement customer validation with Form Builder in angular2?

My registration form in angular2 is created using <form>. Here's how it looks:

<form [formGroup]="RegisterForm3">

                    <ion-item>
                        <ion-label>Last Date:</ion-label>
                        <ion-input formControlName="LastDate" min="2016" type="date"></ion-input>
                    </ion-item>
                    <hr/>
                    <ion-item>
                        <ion-label>Next  Date:</ion-label>
                        <ion-datetime displayFormat="MM/DD/YYYY" formControlName="NextDate" (OnChanges)="npay()"></ion-datetime>
                    </ion-item>
                    <span style="color:red" *ngIf="!RegisterForm3.controls.NextPayDate.valid &&  (!RegisterForm3.controls.NextDate.dirty || submitAttempt)"> * Next day Must Be Greater Than Today's Date </span>
                    <hr/>
                    <ion-item>
                        <ion-label>SecondDate:</ion-label>
                        <ion-datetime displayFormat="MM/DD/YYYY" formControlName="SecondDate"></ion-datetime>
                    </ion-item>
                    <hr/>
                    <ion-item>
                        <ion-label>Original Date:</ion-label>

                        <ion-datetime displayFormat="MM/DD/YYYY" formControlName="RequestedDate"></ion-datetime>
                    </ion-item>
                    <span style="color:red" *ngIf="!RegisterForm3.controls.RequestedDate.valid &&  (!RegisterForm3.controls.RequestedDate.dirty || submitAttempt)"> * RequestedDate Should Be 5 days Greater Than Today's Date </span>
                </form>

In the form.ts file:

  this.RegisterForm3 = formBuilder.group({           
        LastDate: ['', Validators.required],
        NextDate:['',NextDayValidator.isValid],
        SecondDate: ['',Validators.required],
        RequestedDate:['',OriginalDateValidator.isValid],

    });

I have also implemented two custom validator classes.

import { FormControl } from '@angular/forms';

export class OriginalDateValidator {

    static isValid(control: FormControl): any {
        var todaydate =new Date(Date.now() + (1000  * 60  * 60  * 24 * 10))
        console.log(todaydate);
        let duedate=new Date(control.value);
        console.log(duedate);
        console.log(duedate<todaydate);
       //alert(npay);
        if(!duedate){
           return {
                "is empty": true
            };
        }
        if(duedate<todaydate){

             return {
                "Day must 5day greater then todaydate": true
            };
        }
        return null;
    }

}

A challenge I'm facing is that RequestedDate must be equal to either NextDate or SecondDate. I need to test this condition in my OriginalDateValidator class, but can only access the RequestedDate field in my validators. Is there a way to access NextDate and SecondDate in my validator's class as well? Any suggestions?

Answer №1

To access other controls, you can make use of the formGroup reference like so:

export class AdditionalControlAccess {
  static checkValidity(control: FormControl): any {
    let formGroupReference = control.parent;
    if(formGroupReference) {
      let anotherControl = formGroupReference.get('AnotherControlName');
      console.log(anotherControl.value);
    }

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

What is the reason for restricting a placeholder for an optional property in the interface to only be of type any?

I am facing a challenge with a file containing a single declaration, which is for an interface: interface NamedPerson { firstName: string; age?: number; [propName: string]: any; greet(lastName: string): void; } Everything works perfectly ...

If the condition is met, convert the number in JSON format to text

i have retrieved a JSON array from an API: items:[{ Name: "Status" Value: "3" },{ Name: "Status" Value: "2" }, { Name: "Status" Value: "1" }] then I extract the data ...

React router loader is not functioning correctly when trying to fetch data

My attempt to fetch an array of data from an API is resulting in an empty response within the application. However, when I try the same call in a swagger, it returns the correct array. HomePage.tsx: const HomePage = () => { const books = useLoaderDat ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Gradual decline in content loading due to ngrx store actions with payloads

When dispatching actions to the store, there is a noticeable decrease in content load efficiency from http requests due to incremental deficiencies. Surprisingly, requests that do not involve store logic or handling the content of the http requests themsel ...

Configuring Angular AOT Compilation for Library Integration

Recently, we embarked on a project to create internal NPM packages containing angular components for the purpose of reusing these common angular components across multiple sites. As part of our latest efforts, we are striving to support AOT compilation and ...

Tips for sending a function with arguments in a React application using TypeScript

Is there a way to streamline passing a handleClick function to the son component so that it does not need to be repeated? The code in question is as follows: Mother Component: const Mother = () => { const [selectedOption, setSelectedOption] = useSt ...

Having trouble installing Moment and Material Moment Adapter in Angular?

To customize the date format in datepicker controls, I need to have both Material and Material-Moment-Adapter installed. Here is how I installed moment: npm install moment --save And for Material-Moment-Adapter: npm i @angular/material-moment-adapter How ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

Unable to display Contentful content with Angular Universal (SSR)

I'm currently developing an Angular application with Contentful CMS that requires server-side rendering. Despite following the steps outlined in Angular Universal, I am encountering difficulties as it only renders static content and not the dynamic co ...

Once I introduce ngModel into mat-checkbox, the functionality of 'checked' stops working

When I add an ngModel to my mat-checkbox, the checked = "checked" functionality stops working as expected. The following code will work: <mat-checkbox name="BlackBeard" ngModel checked = "checked"> Zehahaha? </mat-checkbox> However, the foll ...

Angular dynamic array implementation

Essentially, I have an API that returns data when a search is performed. I store this data in an array and display it using ngFor in my HTML. However, whenever I attempt a new search, the same function is called but the HTML does not update to show the ne ...

Modifying the ngFor directives in Angular for a fresh look

I successfully implemented the *ngFor feature and it's functioning properly: <div class="dummy__1" *ngFor="let item of dummy.pic; let i = index"></div> Now, I am looking to modify the class="dummy_1" to produce the following format: < ...

A guide on transforming an Observable of one type into an Observable of a different type

Currently, I am working on an Angular application that utilizes NGRX for state management. One of the challenges I am facing is dealing with a selector that returns an Observable. export const mySelector = createSelector(state, (state: IState) => state. ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Is it possible to transmit an argument to a function without using parentheses?

I am currently working with the following code snippet: this.somePromiseFn<T> // this function is actually a promise .then(res => res as T) .catch(err => this.handleError<T>(err)); handleError<T>(err: HttpErrorResponse) { // pe ...

Optimal method for consistently displaying the contents of a node queue with the help of Bottleneck technology

I am currently utilizing the Bottleneck node package and my goal is to maintain a consistent record of everything in the queue. I am looking for a way to immediately display in a console window whenever a job enters the queue, with the following informati ...

Leveraging Filter in Typescript and Ionic for Object Manipulation

I'm currently utilizing Ionic 3.x framework. I have developed a simple chat application and now I need to implement a feature that allows filtering chats based on specific words. To achieve this, I decided to add a search bar to my application. Here ...

Attempting to sift through information using the *ngFor directive

I've been attempting to filter array data on an Angular table using the w-ng5 package, but it's not yielding any results (empty list). Here are the steps I've taken: npm package You can access the documentation for w-ng5 for Angular here. ...

Issue with data not being assigned to TypeScript class variable

Utilizing an http call to fetch data from the backend, I am able to see the retrieved data in the browser console. However, for some reason, the data is not being assigned to the class variable as expected. The code snippet is shown below: "use strict"; ...