Angular 2 validation issue not functioning as anticipated

Here is a validator function that I have:

export const PasswordsEqualValidator = (): ValidatorFn => {

  return (group: FormGroup): Observable<{[key: string]: boolean}> => {

    const passwordCtrl: FormControl = <FormControl>group.controls.password;
    const passwordAgainCtrl: FormControl = <FormControl>group.controls.passwordAgain;

    const valid = passwordCtrl.value.password === passwordAgainCtrl.value.passwordAgain;

    return Observable.of(valid ? null : {
      passwordsEqual: true
    });
  };
};

This validator is utilized in the following form:

  public signupForm: FormGroup = this.fb.group({
    email: ['', Validators.required],
    passwords: this.fb.group({
      password: ['', Validators.required],
      passwordAgain: ['', Validators.required]
    }, {validator: CustomValidators.passwordsEqual()})
  });

Below is a section of the template where it is implemented:

<div formGroupName="passwords">
  <div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
    <label class="label" for="password">Password</label>
    <input class="input" id="password" formControlName="password" type="password">
  </div>
  <div class="form-control" [ngClass]="{error: !signupForm.get('passwords').valid}">
    <label class="label" for="password-again">Password again</label>
    <input class="input" id="password-again" formControlName="passwordAgain" type="password">
  </div>
</div>

Despite matching passwords, an error is displayed. I’ve explored various solutions to similar issues but many seem cluttered and outdated. Therefore, I am seeking a simpler resolution.

Perhaps a minor tweak is required, yet I am unable to pinpoint it.

Answer №1

Give this a try: When comparing 2 values and the validator is not asynchronous, you can simply return a boolean instead of an Observable.

export const CheckPasswordEquality = (): ValidatorFn => {

  return (group: FormGroup): boolean => {

    const passwordCtrl: FormControl = <FormControl>group.controls.password;
    const confirmPasswordCtrl: FormControl = <FormControl>group.controls.confirmPassword;

    const valid = passwordCtrl.value === confirmPasswordCtrl.value;

    return valid ? null : {
      passwordsNotEqual: true
    };
  };
};

Additionally, consider using this method for best practice:

export const CheckPasswordEquality = (): ValidatorFn => {

  return (group: FormGroup): boolean => {

    const passwordCtrl: FormControl = group.get('password');
    const confirmPasswordCtrl: FormControl = group.get('confirmPassword');

    const valid = passwordCtrl.value === confirmPasswordCtrl.value;

    return valid ? null : {
      passwordsNotEqual: true
    };
  };
};

See a demo here: http://plnkr.co/edit/9PzGSIuBhvNz0fpJxTlS?p=preview

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

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

Top picks for ReactJS Typescript accounts

As a novice programmer, I am working on learning ReactJS/NodeJS/Typescript through project-based practice. Currently, I am developing a social media platform and have encountered an issue. I want to display different random users from my MySQL database in ...

Leveraging the power of the Async pipe within an Angular TypeScript file

Using the async pipe in HTML involves utilizing the syntax "Products$ | async as products". But can we also access these same products in the TypeScript file? Is this possible? ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

The data type does not match the expected type 'GetVerificationKey' in the context of express-jwt when using auth0

I am in the process of implementing auth0 as described here, using a combination of express-jwt and jwks-rsa. However, I encountered an error like the one below and it's causing issues with finishing tsc properly. Error:(102, 5) TS2322: Type 'S ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

Is it possible to integrate Angular 2 with Thymeleaf in a single application?

I'm trying to combine Thymeleaf th: with Angular2 templates, but I'm having trouble getting them to compile together. Is there a way to make them work simultaneously? import {Component, NgModule} from '@angular/core' import {BrowserMod ...

Ways to restrict the values allowed in a TypeScript type?

I have a requirement: type AllowedKeys = 'a' | 'b' | 'c' ... and now I want to define a type where the key has to be one of the values in AllowedKeys. For example: type MyType = { a: number; b: string; c: boolean; d: {} / ...

How can you navigate to a particular page within a Single Page Application using NodeNS?

My NodeJS server is hosting a single page application that was built using Angular5. In certain circumstances, I need to direct users to a specific page within the application. For instance, during a designated time period, I want users to be redirected t ...

Steps to include a Target property in a freshly created MouseEvent

Trying to dispatch a contextMenu event, I've noticed that in the MouseEvent interface for TypeScript, the target property is missing, even though it is documented in the contextMenu documentation. Here's my TypeScript snippet: const emulatedMou ...

While the AWS CodePipeline is executing the script, an error is appearing in the log. Please address this issue and resolve it

This is the content of buildspec.yml: version: 0.2 phases: install: commands: - npm install -g typescript pre_build: commands: - echo Installing source NPM dependencies... - npm install build: commands: - echo Bui ...

Exploring the use of Vue and Typescript - encountering the error message "Property ... is not found in type" twice

In my specific case, I believe the error I am encountering may have a different root cause than the common solutions found for it. Configuration-related issues could be at play. Here is the code snippet: export default { data() { return { asy ...

Deeply nested .map function to update state value

The current state value const [settings, setSettings] = useContext(SettingsContext) Utilizing the .map method on the settings state {settings[categoryIndex]?.config?.map((item: ConfigItem, index: number) => ...

The wildcard syntax for importing statements in Angular 2

I created multiple classes in a single file with the following structure file: myclasses.ts export class Class1 {....} export class Class2 {....} export class Class3 {....} Now I am attempting to import all of them using a wildcard like this import {*} ...

Upon initialization, navigate to the specified location in the route by scrolling

My page has various components stacked one after the other, such as: <about></about> <contact></contact> I am utilizing the ng2-page-scroll to smoothly scroll to a particular section when a navigation link is clicked. However, I a ...

What is the best way to add prefixes to my SCSS style sheets?

After attempting to add prefixes to my scss files, I came across the autoprefixer tool. However, I discovered that it only supports CSS files. Is there a way to utilize autoprefixer with scss files? Here are the commands for Autoprefixer: npm install post ...

What is the best way to capture the current state of Angular's components?

Creating an estimate application using angular-cli, I have a unique concept where users can add a dynamic number of child components. It is essential to store the state and data of these components for future edits and exports. ...

Troubleshooting: Angular 7 POST request not communicating with PHP server

Currently, my Angular 7 application is utilizing HttpClient to send a POST request to a PHP server. The process involves a reactive form collecting user input and then transferring it to a specific URL using the following code snippets: admin.component.ts ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...