I am trying To create custom Validation to match password and ConfirmPassword.
But I am getting the error.
I am new to angular. Please ignore my ignorance.
Is it a good idea to create custom validation to match password and Confirm password? or is there a better way out?
Here is the code. Please help
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, AbstractControl, ValidatorFn, ValidationErrors, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-sample-form',
templateUrl: './sample-form.component.html',
styleUrls: ['./sample-form.component.scss']
})
export class SampleFormComponent implements OnInit {
formattedMessage: string;
passMatch: Boolean;
formValid: boolean;
constructor() { }
ngOnInit() {
this.onChanges();
}
sample: FormGroup = new FormGroup({
inpt: new FormControl(null, Validators.required),
pass: new FormControl("", Validators.required),
cpass: new FormControl("", [Validators.required, this.passwordMatch]),
iagree: new FormControl(null, Validators.nullValidator)
});
onChanges(): void {
this.sample.valueChanges.subscribe(val => {
console.log("======================================");
console.log("PASS : " + this.sample.controls.pass.value);
console.log("CPASS : " + this.sample.controls.cpass.value);
if (this.sample.controls.pass.value == this.sample.controls.cpass.value) {
this.passMatch = true;
console.log("MATCHED");
} else {
this.passMatch = false;
console.log("MIS-MATCHED");
}
this.formValid = this.sample.valid;
console.log("PASS MATCH : " + String(this.passMatch));
console.log("FORM VALID : " + String(this.formValid));
});
}
passwordMatch(group: FormGroup): ValidationErrors | null {
let pass = group.controls.pass.value;
let confirmPass = group.controls.cpass.value;
return pass === confirmPass ? null : { notSame: true }
}
sumbit() {
}
}
I am Getting this error :
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'pass' of undefined
TypeError: Cannot read property 'pass' of undefined
at passwordMatch (sample-form.component.ts:51)
at forms.js:1480
at Array.map (<anonymous>)
at _executeValidators (forms.js:1476)
at FormControl.validator (forms.js:1418)
at FormControl._runValidator (forms.js:4089)
at FormControl.updateValueAndValidity (forms.js:4050)
at new FormControl (forms.js:4656)
at new SampleFormComponent (sample-form.component.ts:25)
at createClass (core.js:31985)
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)
-Ashish