What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the password and confirm password fields in my register component? Here is a snippet from my login.component.ts:

import {FormControl, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      Email: new FormControl('', [
        Validators.required,
        Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
      ]),
      Password: new FormControl('', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20)
      ])
    });
  }

  onSubmit() {
    console.log(this.form);
  }

  onReset() {
    this.form.reset();
  }


}

In the code above, I have shown the login.component.ts file that handles the form fields for email and password. Now, I need assistance adding a control for the password confirm field in the register.component.ts. How should I go about it?

import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor() { }
  register(f){
console.log(f.value)
  }


  form: FormGroup;

  ngOnInit() {
    this.form = new FormGroup({
      User: new FormControl('',
      [Validators.required]),

      Email: new FormControl('', [
        Validators.required,
        Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
      ]),
      Password: new FormControl('', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20)
      ]),
      Confirm: new FormControl('', [
        Validators.required,
        Validators.minLength(8),
        Validators.maxLength(20) ])
    });
  }

  onSubmit() {
    console.log(this.form);
  }

  onReset() {
    this.form.reset();
  }



}

Answer №1

Takwa, if you want to create custom validators to achieve your desired functionality, you can follow this example:

    static customValidator(fieldName: string): ValidatorFn {
        return (control: AbstractControl) => {
            if (!control.value) return null;

            return control.value == control.root.get(fieldName).value ? null : { someError: true };
        }
    }

To apply the custom validator to the Confirm form control, you need to include it in the FormControl definition like this:

 Confirm: new FormControl('', [
        Validators.required,
        Validators.minLength(8),
        this.customValidator("Password"),
        Validators.maxLength(20) ])

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

Develop a reusable input component in Angular

I have developed a custom text component with validation capabilities export class CustomInputComponent implements OnInit{ @Input() formGroup: FormGroup; @Input() label: string; @Input() placeholder: string; @Input() name: string; @Input() errorM ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

Tips for creating a test to choose a movie from the MuiAutocomplete-root interface

I am currently utilizing Material UI with React using Typescript and I am looking to create a test for the autocomplete functionality using Cypress. Here is the approach I have taken: Identifying the Autocomplete component and opening it, Choosing an opti ...

The functionality of this.router.navigate in Angular 15 seems to be off, as it is throwing an error saying it is not

Just have a quick question: Check out this code snippet... import { DOCUMENT } from '@angular/common'; import { Component, HostListener, Inject, NgZone } from '@angular/core'; import { Router } from '@angular/router'; @Compo ...

Accessing a variable within a function in Angular

Recently I started working with Angular and encountered an issue while trying to access a variable inside a function. Below is the code snippet that's causing me trouble: mergeImages() { var imgurl; var canvas: HTMLCanvasElement = this.canv ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

Issue with Angular 2+ removeAt method not functioning properly within a nested component

Currently, I am utilizing model-driven approach for the form in angular4. I have passed a formarray to the child component using @input. However, whenever I try to use removeAt function on it, it throws an error: removeAt is not a function This is wha ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

Generate an observable by utilizing a component method which is triggered as an event handler

My current component setup looks like this: @Component({ template: ` ... <child-component (childEvent)="onChildEvent()"></child-component> ` }) export class ParentComponent { onChildEvent() { ... } } I am aiming to ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

What is the best way to open and view files in an NPM dependency that do not use JavaScript?

I am facing an issue with an NPM project setup where my-config is a dependency of my-api. In the my-config project, there is a line of code that fetches the aws-config.ini file from the etc folder: instance.configs.aws = ini.parse(fs.readFileSync('./ ...

How to automatically select an option in a dropdown based on a condition in Angular 2

Currently, I am constructing a select element within a form using an array of objects. My goal is to have one of the options automatically selected based on a specific attribute of the object (myobject.is_default). The initial template code appears as fol ...

Exporting a value from a class in Angular 2 using TypeScript

import {TranslateService, LangChangeEvent} from "@ngx-translate/core"; class CustomLanguageExporter { public currentLang : string; constructor(private translate : TranslateService) { } public static setLanguage(): string { this.tr ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

Despite enabling CORS for a specific origin, I am still encountering the error message "No 'Access-Control-Allow-Origin'"

In my front-end application, I am using Angular to request API responses from a web API core project. Despite setting up cross-origin resource sharing for both running on different origins, I am still encountering an error stating 'No Access-Control-A ...

Angular 2 Error: Unable to access the property 'value' as it is undefined

Whenever I click on the Submit button, this error pops up in the browser console. https://i.sstatic.net/57a5N.jpg In my application, I am attempting to retrieve information about the code uploaded by a Student. I am at a loss as to why this error is bein ...

When trying to run the npm start command, an error occurs referencing type

I am facing difficulties running my project locally due to broken dependencies, and I'm struggling to find a solution. When attempting to install the node modules, I encountered errors, so I made changes to the following dependencies: "codelyze ...

Limit the field type depending on the value of another field

Consider the following scenario: type ActionType = 'action1' | 'action2' | 'action3'; interface Action { type: ActionType; value?: number | Date; } Is there a method in typescript to enforce restriction ...