Ensuring that passwords match during validation

My goal is to compare the values of the password and confirm password inputs. Even when I enter the same value in both fields, an error saying 'Password does not match' still appears.

Component

validate(): boolean {
    this.appErrors = [];

    if (this.objAppUser.UserName == '') {
      this.appErrors.push({ Title: 'User name cannot be blank.' });
    }
    if (this.objAppUser.LoginName == '') {
      this.appErrors.push({ Title: 'Login name cannot be blank.' });
    }
    if (this.objAppUser.Password == '') {
      this.appErrors.push({ Title: 'Password cannot be blank.' });
    }    
    if (this.objAppUser.Password !== this.objAppUser.ConfirmPassword) {
      this.appErrors.push({ Title: 'Password does not match.' });
    }
    if (this.objAppUser.UserCategoryId == 0) {
      this.appErrors.push({ Title: 'UserCategory name cannot be blank.' });
    }

    if (this.appErrors.length > 0) {
      return false;
    }
    else {
      return true;
    }
  }

HTML

<div>
    <mat-form-field class="width-size">
        <input type="password" matInput [(ngModel)]="objAppUser.password" placeholder="Password" name="passwordCtrl">
    </mat-form-field>
</div>

<div>
    <mat-form-field class="width-size">
        <input type="password" matInput placeholder="Confirm Password" name="confirmpasswordCtrl">
    </mat-form-field>
</div>

Answer №1

If you're looking to streamline your custom validations, consider utilizing the ngx-custom-validators package. It offers a convenient solution for all types of custom validation requirements.

Simply use the directive [equalTo]="password" to compare two input fields easily.

HTML

<form [formGroup]='changePasswordForm' novalidate>
    <div class="ele">
        <label>New Password</label>
        <input type="password" ngModel name="password" #password="ngModel" required>
        <p *ngIf="password.errors?.required">required error</p>
    </div>
    <div class="ele">
        <label>Confirm Password</label>
        <input type="password" ngModel name="certainPassword" #certainPassword="ngModel" [equalTo]="password">
        <p *ngIf="certainPassword.errors?.equalTo">equalTo error</p>
    </div>
</form>

Check out the WORKING DEMO (including both Reactive and Template Driven 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

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Tips for integrating the react-financial-charts library into your React and JavaScript project

While exploring the react-financial-charts library, I discovered that it is written in TypeScript (TS). Despite my lack of expertise in TypeScript, I am interested in using this library in my React+JS project due to its active contributions. However, I hav ...

The change event is not being accounted for in Jest testing methodology

HTML <cxui-multi-select [multiSelectOptions]="filteredCommonTemplatesDropdown" formControlName="commonTemplates" [isSearchable]="true" (searchTextChange)="searchCommonTemplates($event)" class="cxui-select--se ...

How to easily scroll to the top of the previous page in Angular 8

In my Angular 8 application, there are buttons that are meant to take the user back to the previous page when clicked. While the functionality works as expected, I am facing an issue where the page does not automatically scroll to the top upon navigating ...

Angular causing issues with Perfect Scrollbar functionality

In an attempt to enhance the scrollbar in my Angular application, I integrated the following library: https://github.com/zefoy/ngx-perfect-scrollbar Following the guidelines provided in the documentation from the link, I included imports into my app.modul ...

What is the process for defining an opaque type in programming?

[ This is not this ] Take a look at this snippet of code: interface Machine<OpaqueType> { get(): OpaqueType, update(t: OpaqueType); } const f = <U, V>(uMachine: Machine<U>, vMachine: Machine<V>) => { const u = uMach ...

Error: Unhandled Promise Rejection - The hook call is invalid as it can only be used within the body of a function component

Hey there! I've got this component called SidebarMenu that belongs to the drawerContent of Drawer.Navigator. const SidebarMenu: React.FC<SidebarMenuProps> = (props) => { return ( <View style={{ flex: 1 }}> ...

What is the best way to center text within an input field?

I've been attempting to center the text in the span tag within the input field, but using "text-align": center in my css doesn't seem to be working as expected. Interestingly, when I switched the span tag to a paragraph tag, it caused the input ...

Hearken to the modifications in the header of ag-grid

I referenced this example to create a custom header for my https://stackblitz.com/edit/clabnet-ag-grid-rich. Here is how I made modifications to it: I added a button that opens a modal popup to edit the header of a column. Everything works correctly, but ...

Show the alert notification just one time every hour in the event that it occurs

I've been struggling to figure out where I'm going wrong with this implementation. Essentially, errors can occur for various reasons, but I only want to display the alert message once every fifteen minutes. For example, if an error occurs at 7:02 ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

Tips for creating two random numbers on Typescript and verifying if they match

import { Component, OnInit } from '@angular/core'; import { from } from 'rxjs'; @Component({ selector: 'app-play-match', templateUrl: './play-match.component.html', styleUrls: ['./play-match.component.css ...

Unable to activate ngx-scrollbar RTL mode in my Angular application

I have been working on implementing Right-to-Left (RTL) support for scrolling using the ngx-scrollbar package in my Angular project. Unfortunately, I am facing an issue where the scrollbar does not seem to function correctly when in RTL mode. To add ngx-s ...

The navigation bar is malfunctioning on Bootstrap 4.0.0-beta.2 framework

I have recently updated to the latest version of Bootstrap: "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5", "bootstrap": "^4.0.0-beta.2", "core-js": "^2.4.1", "jquery": "^3.2.1", "popper.js": "^1.12.9", As part of this update, I incorporated a navbar: &l ...

Display a unique element depending on the path of the Dynamic Angular Routing

Here are the routes I am working with: /dashboard /dashboard/view-all /dashboard/edit/:id One specific issue I've encountered is related to showing/hiding the EditComponent based on the dynamic router. Typically, I can show/hide Angular components ...

Communicating between two Angular 2 components by passing an object through a service

I am currently developing an Angular 2 beta9 application where I am trying to establish communication between two components. I have a "start" component that consists of a radio box button, and the selected item is supposed to be transferred as an object v ...

Angular components can define global variables for navigation purposes

Here is a navigation link example: <a (click)="mylink(someLink)">SomeLink</a> This link belongs to the following container: <div #someLink class="someLink active"> Container Content </div> The TypeScript code ...

Discover the steps to obtain the css class md-inputfield within primeng by referencing the code: <span class="md-inputfield ">

Sorry for the inconvenience, but I am having trouble locating the md-inputfield class in primeng. It is crucial for me to have access to that class attributes in order to properly debug the text field. Is there any chance of resolving this issue and maki ...

Capturing full-page screenshots with Protractor in Angular 8

Currently, I am facing an issue while trying to capture a screenshot of an Angular page using protractor and mocha. Our team has integrated protractor-screenshot-utils as a dependency and added the necessary code in the conf.js file to modify the browser.t ...

Here is a unique version of the text: "Utilizing Various MAT_DATE_FORMATS

I am facing an issue with multiple date input formats in a component. While most inputs follow the standard MM/DD/YYYY format, one requires a custom format (MM/YYYY). I found guidance here on how to customize the format but now all inputs are displaying wi ...