I encountered an issue in my Angular 12 project while trying to implement a service called customValidation. The purpose of this service is to validate password patterns and ensure that the password and confirm password fields match before submitting the form. However, every time I run the project, I receive an error message stating "TypeError: Cannot read property 'value' of null" from the browser console. This error seems to be pointing to the matchPassword function within the customValidation service. Can anyone help me figure out what I missed?
Below is my customValidation.service.ts code:
export class CustomvalidationService {
constructor() {}
patternValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!control.value) {
return null!;
}
const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');
const valid = regex.test(control.value);
return valid ? null! : { invalidPassword: true };
};
}
matchPassword(c: AbstractControl): { [key: string]: any } {
let passwordControl = c.get(['password']);
let confirmPasswordControl = c.get(['cPassword']);
if (passwordControl!.value !== confirmPasswordControl!.value) {
return { passwordMismatch: true };
} else {
return { passwordMismatch: false };
}
}
}
Here is my registration.component.ts file:
export class userRegisterComponent implements OnInit {
aino: number = new Date().getFullYear();
registerForm!: FormGroup;
submitted = false;
fname = new FormControl('', [Validators.required]);
email = new FormControl('', [Validators.required, Validators.email]);
password = new FormControl('', Validators.compose([Validators.required, this.customvalidator.patternValidator]));
cPassword = new FormControl('', Validators.compose([Validators.required, this.customvalidator.matchPassword]));
uPass = new FormControl('', [Validators.required]);
constructor(
public authService: AuthService,
private customvalidator: CustomvalidationService
) {}
ngOnInit(): void {
this.registerForm = new FormGroup({});
}
// function to submit the registration form
onRegister() {
this.submitted = true;
if (this.registerForm.valid) {
alert(
'Form submitted successfully! \n Check the values in the browser console'
);
this.authService.SignUp('email.value', 'password.value');
console.table(this.registerForm.value);
} else {
alert('Please fill all fields. Thank you!');
}
}
}