Confirm Ng2 password and verify.password

These are the codes I've been working with:

<form [formGroup]="registerForm" novalidate (ngSubmit)="doRegister()">
            <div 
                class="form-group" 
                [ngClass]="{'has-danger': registerForm.controls.email.invalid 
                    && !registerForm.controls.email.pristine}">
                <label>Email</label>
                <input
                  formControlName="email"
                  name="email"
                  [ngClass]="{'form-control-danger': registerForm.controls.email.invalid 
                    && !registerForm.controls.email.pristine}"
                  class="form-control"
                  type="email" />
            </div>
            <div 
                class="form-group"
                [ngClass]="{'has-danger': registerForm.controls.password.invalid 
                    && !registerForm.controls.password.pristine}">
                <label>Password</label>
                <input
                  class="form-control"
                  type="password"
                  formControlName="password"
                  name="password"
                  [ngClass]="{'form-control-danger': registerForm.controls.password.invalid 
                    && !registerForm.controls.password.pristine}" >
            </div>
            <div 
                class="form-group"
                [ngClass]="{'has-danger': registerForm.controls.passwordConfirm.invalid}" >
                <label>Password Confirm</label>
                <input
                  [ngClass]="{'form-control-danger': registerForm.controls.passwordConfirm.invalid}"
                  class="form-control"
                  type="password"
                  formControlName="passwordConfirm"
                  name="passwordConfirm" >
            </div>
            <button [disabled]="!registerForm.valid" class="btn btn-primary" type="submit">Register</button>
        </form>

Here is the initialization part of the form:

this.registerForm = this.formbuilder.group({
        email: ['', Validators.compose([Validators.required, validateEmail])],
        password: ['', Validators.compose([Validators.required, Validators.minLength(5)])],
        passwordConfirm: ['', ]
    })

I am now trying to figure out how to validate the password and passwordConfirm fields, but I'm facing some challenges. I attempted to create a directive for it, but couldn't pass the formcontrol directly into it. Any help on this would be greatly appreciated. Thank you.

Edit:

<div
                class="form-group"
                [ngClass]="{'has-danger': registerForm.controls.password.invalid
                    && !registerForm.controls.password.pristine}">
                <label>Password</label>
                <input
                  formControlName="password"
                  name="password"
                  class="form-control"
                  [ngClass]="{'form-control-danger': registerForm.controls.password.invalid
                    && !registerForm.controls.password.pristine}"
                  type="password"
                  validateEqual="registerForm.controls.passwordConfirm"
                  reverse="true" >
            </div>
            <div
                class="form-group"
                [ngClass]="{'has-danger': registerForm.controls.passwordConfirm.invalid}" >
                <label>Password Confirm</label>
                <input
                  formControlName="passwordConfirm"
                  name="passwordConfirm"
                  [ngClass]="{'form-control-danger': registerForm.controls.passwordConfirm.invalid}"
                  class="form-control"
                  type="password"
                  validateEqual="registerForm.controls.password" >
            </div>

Despite my efforts, the validation doesn't seem to work properly and there are no error messages displayed.

Answer №1

To incorporate the validateEqual directive in your HTML, follow these steps:

<div class="form-group" [ngClass]="{'has-danger': registerForm.controls.password.invalid && !registerForm.controls.password.pristine}">
  <label>Password</label>
  <input formControlName="password" name="password" class="form-control" type="password" [ngClass]="{'form-control-danger': registerForm.controls.password.invalid && !registerForm.controls.password.pristine}" validateEqual="passwordConfirm" reverse="true" >
</div>
<div class="form-group" [ngClass]="{'has-danger': registerForm.controls.passwordConfirm.invalid}">
    <label>Password Confirm</label>
    <input formControlName="passwordConfirm" name="passwordConfirm" [ngClass]="{'form-control-danger': registerForm.controls.passwordConfirm.invalid}" class="form-control" type="password" validateEqual="password" >
</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

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Having trouble accessing the undefined property 'ngOnInit' and 'getData' in Angular while conducting unit tests with Jasmine

Looking to write a unit test for my component file that subscribes to a method in the service layer Homecomponent.ts import { Data } from './../model/data.model'; import { DataService } from './../services/data.service'; import { Comp ...

Utilize object destructuring in React when implementing pagination functionality and incrementing the page by one

Whenever the bottom of this div is reached, I want to add one to the page. However, I keep getting an error saying "use object destructuring" and I'm not sure how to resolve it. Below is the code snippet: const vendorContainer = documen ...

Top Method for Connecting Numerous Dependent HTTP Requests Without the Need for Multiple Subscriptions and Iterations

I'm working on an angular project where I have an API that creates a line item and then loops through to call the API for each modification before firing the print request. Currently, I am using multiple subscribes for this process and I was wondering ...

Alert appearing before the user navigates back using the browser button

Is there a way to display a message to the user before they navigate away from the app by clicking the back button in their browser? In my app, I've disabled the ability for users to go back using the browser's buttons and instead provided intern ...

Switching from environment.ts to environment.prod.ts in an Angular library: A step-by-step guide

My objective is to package an Angular application as a library. The issue arises with 'app1-lib' not having 'fileReplacements', resulting in the compilation of 'app1-lib' always using 'environment.ts' instead of &ap ...

Tips for implementing a scroll event handler in React using TypeScript

On my web page, I have implemented lazy loading with a scroll listener. Within the scrollHandler function, I need to define the event type. const scrollHandler = (e: any) => { let scrollHeight = e.target.documentElement.scrollHeight; let ...

Angular 6 powered full stack web application that functions flawlessly on Chrome browser

Currently, I am in the process of constructing a full stack web application focused on data visualization with the use of Angular 6, Django 2.1, Python 3.5, and Postgresql. You can find the code for this project here: https://github.com/shivkiyer/dataviz ...

Display Google font as SVG path but encapsulate within a promise

I'm facing an issue with the following script, where it performs an async operation. My goal is to wrap it in a promise, but I'm unsure about the right approach. static convertGoogleFontToSVG(): Promise<string> { const url = 'htt ...

Setting up the propTypes for interface in React TypeScript

How can I specify the correct PropTypes for a property that is an interface in TypeScript with PropTypes? Requirements - Implementing both TS and PropTypes. Goal - To have a more precise type definition than PropTypes.any that meets standard eslint an ...

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

https://i.sstatic.net/uIksi.jpg In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from &ap ...

What is the best way to implement an EventHandler class using TypeScript?

I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events. To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like thi ...

Which is better for dynamically presenting data: Angular2, React, or plain jQuery?

As someone relatively new to the world of web development, I am eager to explore the different technologies available that facilitate the following functionalities: Displaying user-specific data from a database without requiring page refresh Filtering da ...

Enforcing a discriminated union's match requirements

Challenging Situation I'm new to typescript and facing the task of converting the mapProps function provided below into typescript const addOne = x => x + 1 const upperCase = x => x.toUpperCase() const obj = { entry: 'legend', f ...

Combining Angular 1.3.4 and Angular 2 - A comprehensive guide

Currently, I have an application built on Angular 1.3.4 and my goal is to gradually transition it to Angular 2, module by module. For instance, if there are 5 modules on my webpage, I want to move one module to Angular 2 while keeping the other modules ru ...

How to optimize CSS loading in Angular 15

I am developing an Angular application with Server-Side Rendering (SSR). How can I preload/prefetch the entire styles.css file by adding <link rel="preload" href="/styles.css" as="style" /> to the head section or Link h ...

Tips on how to retrieve the name of the currently selected mat expansion panel using Typescript

Utilizing mat-expansion panel, I have successfully bound the panel title dynamically. Whenever a user clicks on a mat-list item, I need to retrieve the corresponding panel name and display it in another div. Can someone assist me in capturing the active/ ...

The combination of TypeScript output is not working as expected

Here is my current configuration: tsconfig.json { "compileOnSave": true, "compilerOptions": { "module": "none", "outFile": "js/app.js" } } MyApp.Main.ts class Main { constructor() { Utilities.init(this); ...

Why is the value always left unused?

I am having an issue with handling value changes on focus and blur events in my input field. Here is the code snippet: <input v-model="totalAmount" @focus="hideSymbol(totalAmount)" @blur="showSymbol(totalAmount)" /> ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...