Angular 4 validators failing to trigger for custom form validation

I am struggling to implement custom validation for checking if passwords match. Unfortunately, the custom validator is not being triggered. I apologize for not being able to provide a Plunkr example.

//Below is the code snippet for the register component (including imports)

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { confirmPass } from '../confirm-password.validator';


register_form: FormGroup;

  constructor(
    private _fb: FormBuilder
  ) {
    this.register_form = this._fb.group({
      'name': ['', Validators.required],
      'surname': ['', Validators.required],
      'email': ['', [Validators.required, Validators.pattern('/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/')]],
      'password': ['', [Validators.required, Validators.minLength(8)]],
      'confirm_password': ['', [Validators.required, confirmPass]],
      'phone': ['', Validators.required],
      'birth_date': ['', Validators.required]
    },)
  }

//validator function

import { AbstractControl, ValidatorFn } from "@angular/forms";

export function confirmPass(controller): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        console.log(controller.root.controls['password']);
        if (controller.value == controller.root.get('password').value) {
            return null;
        }
        return { 'error': { value: controller.value } };
    };
}

Answer №1

To ensure password security, it is important to include both a password and confirmation password in the group.

Your function should look something like this:

this.register_form = this._fb.group({
  'name': ['', Validators.required],
  'surname': ['', Validators.required],
  'email': ['', [Validators.required, Validators.pattern('/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/')]],
  'password_group':this.formBuilder.group(
  {
    'password': ['', [Validators.required, Validators.minLength(8)]],
    'confirm_password': ['', [Validators.required, confirmPass]]
  },
  {
    validator: this.passwordConfirming
  }),
  'phone': ['', Validators.required],
  'birth_date': ['', Validators.required]
})

Password validation function:

 passwordConfirming(c: AbstractControl): { invalid: boolean } {
   if (c.get('password').value !== c.get('confirm_password').value) {
     return {invalid: true};
   }
 }

Additionally, remember to use formGroupName in your HTML code

For example:

<div class="form-group row" formGroupName="passwords">
 // Include input fields for password and confirmation password here
</div>

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

Extract data from recurring rules

I am dealing with an object that is structured like this: const input = { "recurrence": { "rrule": [ "RRULE:FREQ=DAILY;UNTIL=20230606T133000Z" ], } }; My goal is to extract the value stored in FREQ and determ ...

The browser is failing to load the login page, however, the method is functioning properly when accessed through Postman

I am facing an issue in my angular project with the login component - it is not loading the login page and instead showing a HTTP ERROR 401. Curiously, when I try to log in using Postman, everything works perfectly fine. However, I can't seem to figu ...

What steps can be taken to prioritize files with specific extensions in webpack?

I have a dilemma with two files: - somefile.scss - somefile.scss.ts When importing the file in my typescript code, it is referencing the wrong one: import styles from "somefile.scss" The typescript part works fine with the correct import (.scss ...

Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method. For instance, let's say I have four options: A B C D In my method (let's use "x" as an example): if(name == A) { disable the selection for option A. ...

Why does TypeScript permit the storage of incorrect types?

Utilizing Typescript within NodeJS has presented a challenge for me. I defined an interface and assigned it to a variable. However, when I attempt to pass data that does not align with the type specified in the interface - such as passing a number instead ...

Sending data to the server using AngularJS 1.x and Typescript

I am encountering an issue where the header values I'm trying to post to the server are not properly embedded in the request header, resulting in incorrect answers. I understand that there is a mistake in my approach, but I can't seem to pinpoint ...

A foundational NodeJS program in TypeScript featuring a structured client-utility-definition setup with adherence to stringent coding guidelines

What is the best way to set up a basic TypeScript framework for starting a program with strict settings, based on the following program structure? An initial "client" code containing the actual program logic A separate "utility" module for defining funct ...

Retrieving response body from Angular HTTP request

I am currently trying to understand how to retrieve the response body. In the network console of the browser, I can view it as an array of strings (which is what I want to get), but my code only returns an Object: this.http.request(req).subscribe(event =& ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

Style will be applied to Angular2 when the object's ID exceeds 100

I am working with object markers that have different Id's assigned to them. Now, I am trying to apply additional styling when the id > 100. Check out the code snippet below: <span *ngIf="result.object.reference > 100" class="tooltip-data"&g ...

What steps should I follow to set up my app to utilize the Django phonenumber field module effectively?

Currently working with Django 2.0 and Python 3.7, utilizing the Django PhoneNumber field extension found here: https://github.com/stefanfoulis/django-phonenumber-field. Below is an excerpt of how I have set up my model: ...

Tips for converting Promise<Document[]> in JavaScript / TypeScript?

After executing a lengthy MongoDB query, I have obtained the result: const data = collection.find({}).project({ name: 1 }).toArray() The type of this result is Promise<Document[]> I attempted to perform a transformation on it, but encountered dif ...

Encountering CORS Error Despite Having CORS Enabled in Nest.js/Angular Application

Currently, I am in the process of developing a small calculator application as a means to gain expertise in Nest.js and Angular. In order to achieve this, I have established a server that hosts a basic web API equipped with several endpoints. One particula ...

What is the rationale behind allowing any type in TypeScript, even though it can make it more challenging to detect errors during compile time?

Why is it that all types are allowed in TypeScript? This can lead to potential bugs at runtime, as the use of type "any" makes it harder to detect errors during compilation. Example: const someValue: string = "Some string"; someValue.toExponentia ...

Ensuring radio button validation using parsley.js

I am attempting to validate radio buttons using parsley.js. Below is the code snippet I am working with: <p id="registration_field_custom2" class="onefield registration_field_custom2"> <span class="doyou"> <span class="text">etc et ...

Issue encountered following npm install and ng new on an Angular project: Error Notification

Since Tuesday, I've been experiencing some difficulties. Currently learning Angular and working on multiple projects daily :D Unfortunately, as of Tuesday, I've been unable to run ng new, npm install, or even ng serve. I've attached screens ...

Exploring Geographic Navigation with Angular Maps

Currently, I'm implementing Google Maps into my Angular SPA by following this helpful article. The HTML code in app.component.html looks like this: <html> <head> <meta charset="utf-8" /> <title>Map</titl ...

Eliminate the ngIf directive based on two different conditions

I need to execute the onRemoveLastTag() method under two specific conditions. I want the method to be triggered only when the form is empty and the user presses the keyup.backspace key combination. The backspace key should function normally as long as the ...

What could be causing my Jasmine test to not run the application code within a for loop?

Imagine having a straightforward function that includes a for statement: public loadImages(images): void { for (let image of images) { this.imageLoader.load(image['url']); } } When attempting to spy on imageLoader.load, the test ...

What is the best way to create an input that restricts only specific names from being entered

Hello all, I have come across the following code snippet : <v-file-input class="mx-6" show-size accept=".xlsx" label="File input" @change="selectFile" ></v-file-input> ...