Issue
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-user-register',
templateUrl: './user-register.component.html',
styleUrls: ['./user-register.component.css']
})
export class UserRegisterComponent implements OnInit {
registerationForm: FormGroup = new FormGroup({});
constructor() { }
ngOnInit() {
this.registerationForm = new FormGroup({
userName : new FormControl(null, Validators.required),
email : new FormControl(null, [Validators.required, Validators.email]),
password : new FormControl(null, [Validators.required, Validators.minLength(8)]),
confirmPassword : new FormControl(null, [Validators.required]),
mobile : new FormControl(null, [Validators.required, Validators.minLength(10)])
}, this.passwordMatchingValidatior);
}
passwordMatchingValidatior(fg: FormGroup): Validators{
return this.registerationForm.get('password').value === this.registerationForm.get('confirmPassword').value ? null : {notmatched: true};
}
onSubmit(){
console.log(this.registerationForm);
}
}
error message
Error: src/app/user/user-register/user-register.component.ts:24:5 – error TS2322: Type ‘{ notmatched: boolean; } | null’ is not assignable to type ‘Validators’.
Type ‘null’ is not assignable to type ‘Validators’.
24 return this.registerationForm.get(‘password’).value === this.registerationForm.get(‘confirmPassword’).value ? null : {notmatched: true};
Error: src/app/user/user-register/user-register.component.ts:24:61 – error TS2531: Object is possibly ‘null’.
24 return this.registerationForm.get(‘password’).value === this.registerationForm.get(‘confirmPassword’).value ? null : {notmatched: true};
Solution
According to angular docs – Adding cross-validation to reactive forms
create your validator
export const passwordMatchingValidatior: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
return password?.value === confirmPassword?.value ? null : { notmatched: true };
};
and update formgroup validator
this.registerationForm = new FormGroup({
userName: new FormControl(null, Validators.required),
email: new FormControl(null, [Validators.required, Validators.email]),
password: new FormControl(null, [Validators.required, Validators.minLength(8)]),
confirmPassword: new FormControl(null, [Validators.required]),
mobile: new FormControl(null, [Validators.required, Validators.minLength(10)])
}, { validators: passwordMatchingValidatior });