What could be causing the issue with the custom validator in Angular 4 FormGroup not functioning

Having trouble incorporating a custom validator formValidator() on a form group. I am setting the errors to {invalidData: true} based on a certain condition, and clearing them when the condition is false. However, the issue arises with 'control2' which already has a required validator. Clearing the errors for 'control2' also removes the required validator.

Take a look at the code snippet below:

createReactiveForm(data: any) {
    const formGroup = new FormGroup({
        'control1': new FormControl(data.value1),
        'control2': new FormControl(data.value2, [Validators.required])
    }, this.formValidator());
}

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        const control1 = group.controls['control1'];
        const control2 = group.controls['control2'];
        if (control1.value === 'ABC' && control2.value !== 'ABC') {
            control2.setErrors({ invalidData: true });
        } else {
            control2.setErrors(null);
        }
        return;
    };
}

Do you have a solution for this issue? Is there something wrong with my custom validator implementation? Your assistance is greatly appreciated.

Answer №1

Validation functions should not assign errors to controls. Their role is to produce validation error objects.

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        // utilize the framework's abstraction
        const control1 = group.get('control1');
        const control2 = group.get('control2');
        // determine the appropriate result based on conditions
        return control1.value === 'XYZ' && control2.value !== 'XYZ' ? 
          { incorrectInput: true } : null;
    };
}

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

Run the code before the http observable initiates the network request

Is there a way to write code that executes before an Angular HTTP client observable makes a network call, but after the function is called? The following code snippet shows an example of an Angular HTTP service call: this.geocodeApi.getAddressSuggestions( ...

"Dealing with conflicts between RMQ and TypeORM in a NestJS

Every time I try to use TypeOrm, RMQ crashes. I can't figure out why. Utilizing the library golevelup/nestjs-rabbitmq has been a struggle for me. I've spent 7 hours trying to resolve this issue. @Module({ imports: [ ConfigModule.f ...

Injecting Dependencies into an Angular 6 Service

Within my typescript file, I have a collection stored in an array. component.ts list: any[]; constructor( private listProcessor: ListProcessor ) {} ngOnInit() { this.listProcessor.getListItems() .subscribe( res => { th ...

Encountering issues in Angular 2 when attempting to pass data into root component through ng-content and binding. Objective: Creating a reusable form component

I currently have a .NET MVC application and I'm looking to integrate Angular 2 into it. The structure of my page is as follows: <html> <head>css imports and jquery imports</head> <body> <div> a bunch of table ...

Angular 2 Observables consistently deliver undefined results

I keep encountering an issue where I am always receiving 'undefined' in my component code. Any assistance on this matter would be greatly appreciated. When I attempt to write to the console, it consistently returns 'undefined'. I am c ...

Suggestions for resolving this problem when attempting to add an item to an array

I am currently working on a form that allows users to add items into an array list. However, I am facing an issue where if a user chooses to add more devices into the array and changes the model type, the code counts it as part of the previous array if the ...

Create an entity with a field that holds a value type based on the value of another key field

Essentially, I am looking to create a customized "Pair" data type For example: type Pair<T extends Record<string, string | number>, K extends keyof T> = { field: K, value: T[K] } So, if we have: type Rabbit = { name: string, a ...

When there is only one value, the BehaviorSubject can be hit multiple times

Recently, I implemented BehaviourSubject in a shared service to retrieve the current value when clicking a button. Everything seems to be working fine, however, there are instances where the API call within the subscribe block of BehaviourSubject is being ...

Navigating to a specific attribute within a higher-level Component

Within my top-level Component, I have a property that is populated with data from an HTTP source. Here is how it is implemented in a file named app.ts: import {UserData} from './services/user-data/UserData'; Component({ selector: 'app& ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

Tips for creating a Single Xpath instead of Multiple paths

I'm currently working with Protractor alongside TypeScript. I have an element located at: xpath = "**//div[@class='loglist']/div[1]/div[2]**" Afterwards, there are additional elements that need to be identified in different divs s ...

What sets template-driven and reactive forms apart in practice?

Exploring the Angular2 new Forms API has revealed two distinct approaches to forms: Template driven and reactive (model-driven) forms. I am curious about the real-world differences between these two methods, beyond just syntax. Which approach is more adva ...

Having trouble launching my Angular project

After encountering issues with my Angular project, I decided to reinstall Node.js and Angular CLI. However, when attempting to run ng serve, I was met with this error: view the image here I conducted a thorough search on Google for a solution, which direc ...

Using variables to replace 'placeholders' in Typescript with string interpolation

Seeking a definitive answer on this matter, I pose the question: In C#, an example of which would be as follows: var text = "blah blah"; var strTest = String.Format("This is a {0}", text); //output: 'This is a blah blah' How can I accomplish t ...

Unable to locate the pipe within the customized component - Ionic 3 with Lazy Loading

In my Ionic 3 project, I have organized my pipes into a pipes.module.ts file and imported it in @NgModule for all my lazy loaded pages, which works perfectly without any issues. However, when I tried using the same approach in a custom component and used ...

Winston logs are unable to function within the Docker Container

I'm currently working on developing a nodejs/express app with typescript and have recently installed the winston package using npm install winston. I came across this helpful article that I've been following closely. Now, my goal is to dockerize ...

Setting an initial value from an observable and allowing for customization later

As I delve into the world of reactive development in Angular, it has mostly been a smooth journey. However, there are certain aspects that have proved to be more challenging than anticipated. One particular requirement involves displaying a list of items ...

Issues with CORS arise when using certain special characters in the URL

In my current web application, I have Angular on the client side and AWS API Gateway on the server side. I've encountered an error message: Access to XMLHttpRequest at <my destination> from origin <my origin> has been blocked by CORS pol ...

The compilation fails when using TestUtils findRenderedComponentWithType with a Component<Props> definition

Content of the file package.json: { "scripts": { "test": "tsc --project . --noEmit" }, "dependencies": { "@types/react": "^16.7.6", "@types/react-dom": "^16.0.9", "react": "^16.6.3", "react-dom": "^16.6.3", "typescript": "^3. ...

RouterLink element

The RouterLink directive selector specified in the official documentation is :not(a):not(area)[routerLink]. This means that it will select all elements with a routerLink attribute that are not anchor or area elements. Is my understanding correct? Given th ...