What is the process for including extra validators within the ngOnInit function?

I am working on an Angular component where I am adding some validators to the form in the constructor. However, I would like to add additional validators in my ngOnInit method. How can I accomplish this?

   export class ResetPasswordComponent implements OnInit {
      constructor(
        private fb: FormBuilder,
        private route: ActivatedRoute,
        private forgotPasswordService: ForgotPasswordService,
        private configService: ConfigService,
        private usersService: UsersService
      ) {
        this.blacklistedPasswords = this.configService.config.blacklistedPasswords;

        this.formGroup = this.fb.group(
          {
            password: ['', [Validators.required, Validators.minLength(8)]],
            confirmPassword: ['', [Validators.required, Validators.minLength(8)]]
          },
          {
            validator: Validators.compose([
              passwordStrengthValidator('password', 'confirmPassword'),
              blacklistedPasswordValidator(
                'password',
                'confirmPassword',
                this.blacklistedPasswords
              )
            ])
          }
        );
      }


ngOnInit() {

}
    }

How can I append another validator to the component's ngOnInit method? For example, I want to add a validator like matchingValidator('password', 'confirmPassword'), similar to passwordStrengthValidator and blacklistedPasswordValidator. How can I achieve this?

I am new to Angular, so thank you for your help!

Answer №1

To add a new validator, you can simply use the following approach:

ngOnInit() {
  this.formGroup.setValidators(Validators.compose([this.formGroup.validator, customValidator('field1', 'field2')]));
}

Make sure to include all current validators when calling setValidators, as it will replace any existing validators with the ones you specify. I hope this explanation helps.

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

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...

Comparing dates in Angular and Ionic: A breakdown

I am facing an issue with comparing dates in my ion-datetime input and a date variable obtained from the server. The problem arises because when I retrieve the value from the input, it includes the time field along with the date. As a result, using the get ...

Using Angular's typeahead with RxJs switchMap for subscribing to data sources

Implementing the Angular bootstrap Typeahead plugin for displaying colors. However, I am facing difficulty in resolving circular references like I have done in other parts of my project. The RxJs SwitchMap operator is not working for me in this case. Are t ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Issue encountered with Syncfusion ej2-angular Pivot Table when using subtraction operator - ERROR SyntaxError: Invalid operand in postfix operation

I encounter issues specifically when utilizing the minus operator calculatedFieldSettings: [ { name: 'Binaural', formula: '"Sum(the_order_count)" == "0" ? "0" : ("Sum(the_unit_count)" - "Sum(the_order_count)") / "Sum(the_order_count)" ...

Creating a unified environment variable for Angular 2 and ASP.NET Core MVC: A comprehensive guide

In my ASP.NET Core MVC project, I am utilizing an Angular 2 application. Both the Angular 2 app and the Startup.cs file contain code that is specific to different environments. For example, using http://localhost as the web service URL during development ...

Jasmine-core steers clear of incorporating angular-devkit/build-angular into its installation process

Upon running ng serve, an error related to angular-devkit has surfaced. As a result, I proceeded to install it, but encountered the following error: npm install @angular-devkit/build-angular npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to re ...

Tips on retrieving data from an http request in Angular 2 after it has been successfully made

Consider this example function: getSessionInfo() { this._http.get(someCorrectUrlHere) // It is unclear what this map function does .map(res => res.json()) // It is unclear what this subscribe function does .subscribe( data = ...

When using CSS Modules with next aliases, the class names will not be automatically autocompleted if the CSS file is located outside the

When working on a NextJS project using VSCode with the CSS Modules extension and path aliases, I encountered an issue with autocompletion for classNames. While autocompletion works fine for files without path aliases, it does not show up when importing fil ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

Is it a good idea to integrate TypeScript with JavaScript before uploading to the server?

Our team has been exclusively using nodejs and writing code in vanilla JavaScript with a .js extension. While everything was running smoothly, we've recently made the decision to switch to TypeScript for our nodejs app development. However, we are fac ...

Exploring the combination of Angular 2 and Webpack 2 for dynamic

I've been struggling to add a background image to my HTML template, but it's not showing up. I've searched through internet forums, webpack documentation, and Angular docs, but I haven't been able to find a solution that works. My webp ...

Peer Dependency Issue Detected in My Angular Project

Whenever I run the command below, I receive the following messages: npm install --save @angular/animations --> +-- UNMET PEER DEPENDENCY @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3d31332e37323b2c1e6b706c70 ...

What is the outcome when the return type is a string or a function that takes validation arguments and returns a string?

This excerpt is extracted from line 107 over here. From my understanding, it indicates: The function either returns a string directly or a function that accepts ValidationArguments as input and then produces a string output. Given that this is new to m ...

Can someone confirm if I am importing this png file correctly? I am encountering an error with Vite, here is my code

Error: TypeScript+ React + Vite [plugin:vite:import-analysis] Failed to find import "./assets/heropic.png" in "src\components\Hero.tsx". Are you sure the file exists? Hello fellow developers! I am new to working with react and typescript. Curren ...

Unable to retrieve template generated using the innerHTML directive in Angular 4

I am in need of accessing the elements of a dynamically created component's DOM through the innerHTML directive in Angular. Below is my main component: import {Component} from '@angular/core'; @Component({ selector: 'app-root', ...

Implement a personalized auto-fill feature in Angular triggered by a user's

I am looking to implement a customized autocomplete feature on an input element in Angular 8. Currently, I have the following setup to capture the tab key press: <input (keydown.Tab)="onKey($event)" /> Then, in my .ts file, I have the following me ...

What is the best approach to develop a React Component Library adorned with Tailwind CSS and enable the main project to easily customize its theme settings?

Currently, I am in the process of developing an internal component library that utilizes Tailwind for styling. However, a question has arisen regarding how the consuming project can incorporate its own unique styles to these components. Although I have th ...

Transforming API response data into a Typescript object using React mapping

When I make an API call, the response data is structured like this: [ { "code": "AF", "name": "Afghanistan" }, { "code": "AX", "name": "Aland Islands" } ...

Using RxJs: switchMap conditionally based on the emitted value being empty

Below is the code snippet I am currently dealing with: const id = 1; // id = 2 of([{id: 1, name: 'abc'}]).pipe( map(items => items.find(item => item.id === id)), switchMap(item => item ? of(item) : this.makeHttp ...