I was trying to create a password reset form where I needed to create two fields for a new password and confirming the new password. I was testing whether they are same or not using custom validation in angular2, but my code is not working. I am attaching my component file and custom validation class here, can anyone please suggest me what can be the proper solution to it.
I am using angular 2.4
Component Code:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
import { Checkpassword } from '../checkpassword';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
signUpForm: FormGroup;
constructor(fb: FormBuilder) {
this.signUpForm = fb.group({
oldpassword: ['', Validators.compose([
Validators.required,
Checkpassword.checkPasswordLength
])],
newpassword1: ['', Validators.required],
newpassword2: ['', Validators.required]
}, {validator: Checkpassword.isSamePassword});
}
ngOnInit() {
}
}
Custom Validator Code:
import { FormControl, FormGroup } from '@angular/forms'
export class Checkpassword {
static checkPasswordLength(control: FormControl){
if(control.value.length > 0 && control.value.length < 5 ) return {smallPassword: true};
return null;
}
static isSamePassword(group: FormGroup){
let newpassword1 = group.controls['newpassword1'].value;
let newpassword2 = group.controls['newpassword2'].value;
if(newpassword1 !== newpassword2){
return {notSamePassword: true};
}
return null;
}
}