Password validations are a key feature of reactive forms

Currently, the sign-up button only becomes enabled if the signup form is valid. However, I am facing an issue where the button is getting enabled even when the password and confirm password fields do not match.

I suspect there might be a problem with my implementation of this.equalWithPasswordValidator(). Any thoughts on what could be causing this issue? Thanks in advance.

#html code

 <button mat-raised-button class="full-width v-btn-lrg mt-0px" color="primary" type="submit"
            [disabled]="signupForm.invalid">
            {{labels.BUTTON.SETUP}}
          </button>

#ts code

    this.signupForm = this.fb.group({
      confirmPassword: [
        '',
        [Validators.required, this.equalWithPasswordValidator.bind(this)],
        
      ],
      password: [
        '',
        [
          this.validatePasswordRequired,
          this.validateMinimumPassword,
          this.validatePasswordUpperCase,
          this.validatePasswordLowerCase,
          this.validatePasswordSpecialCharacter,
          this.validateOneNumber,
        ],
      ],
    });
  }

  equalWithPasswordValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const equal = control.value === this.signupForm.get('password').value;
      return equal ? { notEqual: { value: 'Passwords do not match' } } : null;
    };
  }

Answer №1

To access both controls in a FormGroup, you must apply a validator. Here is one way to create a validator that compares two fields...

  // Form Component

  form = new FormGroup({
    password: new FormControl('', [ yourValidators... ]),
    confirmPassword: new FormControl('', [ yourValidators... ])
  }, {
    validators: [ equivalentValidator('password', 'confirmPassword') ]
  });


  // equivalent.validator.ts

  import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
    
  export const equivalentValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
    
    return (control: AbstractControl): ValidationErrors | null => {
      const firstControl = control.get(firstControlName);
      const secondControl = control.get(secondControlName);
    
      if (secondControl.value && secondControl.value !== firstControl.value) {
        secondControl.setErrors({ notEqual: true });
      }
    
      return null;
    };
    
  };

In this scenario, an error is only set on the second field if it does not match the first. Instead of defining the error message directly, an error label of notEqual is assigned so the validator can be utilized across multiple forms.

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

Guide on enabling the Access-Control-Allow-Origin feature for Angular 5 and Node.js:

After exploring various methods to include 'Access-Control-Allow-Origin', I have not been successful in resolving the issue. I am utilizing the @angular/common/http module with an external URL as a data source. However, when attempting to retrie ...

Resolving the error message "Default props must have construct or call signatures for 'Component' in Typescript"

I'm currently working on a function component called MyComponent and I'm facing an issue with setting a default prop for component. The goal is to have the root node render as a "span" if no value is provided. However, I am encountering the follo ...

Change the ddmmyy date string to dd/mm/yyyy format using TypeScript

When I use the date picker onchange method, the date is passed as a string like ddmmyyyy (20102020) to dd/mm/yyyy. I am unsure of how to convert the date format from ddmmyyyy to dd/mm/yyyy. In the CustomDateParserFormatter, the string needs to be converted ...

Component that can be used multiple times to load data

I am currently working on a react/nextjs/redux application where each component needs to call a different backend API. The main challenge I am facing is the lack of reusability in loading data components due to some repetitive code that I would like to el ...

Adjusting the width of row items in Angular by modifying the CSS styles

I am envisioning a horizontal bar with items that are all the same width and evenly spaced apart. They can expand vertically as needed. Check out the updated version here on StackBlitz https://i.sstatic.net/MFfXd.png Issue: I am struggling to automatica ...

Angular fails to detect newly added component

Just dipping my toes into the world of angular and decided to create my first app tour of heroes. However, I encountered a problem where angular wasn't recognizing a new component. Instead of throwing an error, it simply refused to render in the brows ...

Avoiding the ESLint error of missing return type in a React TypeScript function

My JavaScript function looks like this: export default () => ({ root: css` background-color: hotpink; margin-bottom: 1.45rem; `, }); However, ESLint is raising a complaint: Missing return type on function.eslint@typescript-eslint/explicit-m ...

The NavBar element is failing to update when the state changes

I have been working on developing a shopping cart feature. As I implemented a context and passed the state as a value to increment and decrement buttons in the cart, everything seemed to be functioning well with item counts adjusting accordingly. However, ...

Make sure to send individual requests in Angular instead of sending them all at once

I am looking to adjust this function so that it sends these two file ids in separate requests: return this.upload(myForm).pipe( take(1), switchMap(res => { body.user.profilePic = res.data.profilePic; body.user.coverPic = res.data.coverPic; ...

Every time a new message is sent or received, I am automatically brought back to the top of the screen on the

I'm currently working on integrating a chat feature into my Angular Firestore and Firebase app. Everything seems to be functioning well, except for one issue - whenever a new message is sent or received, the screen automatically scrolls up and gets st ...

Mastering the incorporation of Context in React with Typescript

I am currently in the process of setting up a context provider for my Next.js application using TypeScript. Although I have previously set up a context provider in React using plain JavaScript, this time I am delving into learning TypeScript. In the code ...

Personalize or delete the spacing within an ion row

Currently, I am delving into the world of Ionic app development. Although I have grasped the concept of the Grid layout, I find myself hitting a roadblock when it comes to adjusting or removing spaces between rows 2 and 3 in my app interface, as illustrate ...

Will a JavaScript source map file continue to function properly even after the source code file has been minified?

My experience I specialize in utilizing TypeScript and Visual Studio to transform highly organized code into functional JavaScript. My skills involve configuring the project and Visual Studio to perform various tasks: Merging multiple compiled JavaScrip ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

Is there a way to verify if this route leads to a valid page?

I am currently using Angular 5 along with localize-router. Unfortunately, localize-router does not support paths without a language prefix (only the main page), so I decided to create a component to handle this issue. In my router configuration, I have set ...

Guide on merging paths in distinct modules within an Angular project

I am looking to merge two sets of routes from different modules in my application. The first module is located at: ./app-routing.module.ts import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; i ...

A TypeScript class transferring data to a different class

I have a set of class values that I need to store in another class. function retainValues(data1,data2){ this.first = data1; this.second = data2; } I am looking for a way to save these class values in a different class like this -> let other = N ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...