1

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
            }
        });
    }
slavoo
  • 5,798
  • 64
  • 37
  • 39
  • Possible duplicate of [password and confirm password field validation angular2 reactive forms](https://stackoverflow.com/questions/43487413/password-and-confirm-password-field-validation-angular2-reactive-forms) – Lab Lab Aug 23 '17 at 07:58
  • Have you tried anything yet? It seems like you're most of the way there. I assume your specific question is what Validator to use, is that correct? – DaveyDaveDave Aug 23 '17 at 07:58
  • 1
    @DaveyDaveDave Yes i tried many examples but end up with many errors. – Mubashir Tahir Aug 23 '17 at 08:19
  • You need to post what you tried, with the errors, and ask a specific question. When that is answered, if further specific questions remain, ask those as new questions. Have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask), then edit your question to include the suggestions from there. – DaveyDaveDave Aug 23 '17 at 08:41

1 Answers1

1

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
})
Robert
  • 3,373
  • 1
  • 18
  • 34