Mubashir Tahir
Mubashir Tahir

Reputation: 21

How to add confirm password field in angular 2 form (Tried many examples)

Please someone help me with Angular 2 form. I want to add a confirm password field which can verify password.

Here is my code.

export class SignUpComponent implements OnInit {

    signUpForm: any; 
    result: any;

    constructor(
        private formBuilder: FormBuilder, 
        private accountService: AccountService,
        private router: Router
    ) {}

    ngOnInit() {
        this.signUpForm = this.formBuilder.group({
            username: ['', [Validators.required]], 
            password: ['', [Validators.required]],
            fullName: ['', [Validators.required]],
            email: ['', [Validators.required]]
        });
    }



    save(event: any) {
        this.accountService.create(this.signUpForm.value).subscribe(data => {
            if(data.count == 0) {
                 this.router.navigate(['/login']);
            } else {
                this.result = data
            }
        });
    }

Upvotes: 1

Views: 495

Answers (1)

Robert
Robert

Reputation: 3483

write custom validation

import {AbstractControl} from '@angular/forms';
export class PasswordValidation {

static MatchPassword(AC: AbstractControl) {
   let password = AC.get('password').value; // to get value in input tag
   let confirmPassword = AC.get('confirmPassword').value; // to get value in input tag
    if(password != confirmPassword) {
        console.log('false');
        AC.get('confirmPassword').setErrors( {MatchPassword: true} )
    } else {
        console.log('true');
        return null
    }
}
 }

in your componet add custom validator like this

import { PasswordValidation } from './password-validation';
this.form = fb.group({
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required]
}, {
  validator: PasswordValidation.MatchPassword // your validation method
})

Upvotes: 1

Related Questions