M
M
Muxailo2017-10-24 01:07:22
JavaScript
Muxailo, 2017-10-24 01:07:22

How to do password confirmation in Angular 2?

Hello.
Can you tell me how to confirm the password?
There is an html file with a form and a registration component.
How to check for the identity of Password i confirmPassword?

<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
            <label for="password">Password</label>
            <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
            <div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
        </div>

    <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !repassword.valid }">
            <label for="repassword">RePassword</label>
            <input type="repassword" class="form-control" name="repassword" [(ngModel)]="model.repassword" #repassword="ngModel"  />
            <div *ngIf="f.submitted || repassword.valid===repassword.valid" class="help-block">rePassword is required</div>
        </div>

import { Component } from '@angular/core';
import { Router } from '@angular/router';
 
import { AlertService, UserService } from '../_services/index';
 
@Component({
    moduleId: module.id,
    templateUrl: 'register.component.html'
})
 
export class RegisterComponent {
    model: any = {};
    loading = false;
 
    constructor(
        private router: Router,
        private userService: UserService,
        private alertService: AlertService) { }
 
    register() {
        this.loading = true;
        this.userService.create(this.model)
            .subscribe(
                data => {
                    // set success message and pass true paramater to persist the message after redirecting to the login page
                    this.alertService.success('Registration successful', true);
                    this.router.navigate(['/login']);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                });
    }
}

How to check for the identity of Password i confirmPassword?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
denismaster, 2017-10-24
@denismaster

Use ReactiveForms and a validator that compares the value of one formControl with another formControl, like so:

const confirmPasswordValidator = (controlToCompare: AbstractControl) : ValidationFn => 
  (control: AbstractControl): ValidationResult => {
    let controlValue = control.value
    let anotherValue = controlToCompare.value
    if( controlValue!==anotherValue) return { confirmPassword: true } 
    return null
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question