Currently, I am in the process of setting up a custom validator for a form. This validator will analyze the input from the form and cross-reference it with an array of values to ensure that the input is unique. The array used for this comparison is fetched from an Observable. Unfortunately, when attempting to access the array within the validation method, it appears as undefined. I suspect this issue arises because of the sequencing in relation to the subscribe function, but I have been unable to figure out the correct approach.
Below is a simplified version of the code that illustrates my objective. I've experimented with both of the validator functions provided. Additionally, I have attempted relocating the formgroup definition within the ngOnInit function and directly after populating allUserNames within the subscribe function.
export class userComponent implements OnInit {
user: user = new user;
allUserNames: string[];
generalForm = new FormGroup({
userName: new FormControl(
this.user.name, [
Validators.required,
Validators.maxLength(20),
this.UniqueNameValidator
//,this.UniqueNameValidator1(this.alluserNames)
])
})
constructor(private userService: userService) { }
ngOnInit() {
this.subscribeUsers();
}
subscribeUsers(): void {
this.getUsers().subscribe((users) => {
this.allUserNames = Object.keys(users).map(itm => users[itm].name);
})
}
getUsers(): Observable<user[]> {
return this.userService.getUsers();
}
UniqueNameValidator(allUsers: String[]): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
allUsers.forEach((userName) => {
if (userName === control.value) {
return { 'notUnique': true };
}
});
return null;
}
}
UniqueNameValidator1(control: AbstractControl): { [key: string]: boolean } | null {
this.allUserNames.forEach((userName) => {
if (userName === control.value) {
return { 'notUnique': true };
}
});
return null;
}
}
My expectation is that the validate function should compare the input string and flag it as not unique if a match is found in allUserNames. However, an error keeps popping up:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined
I would greatly appreciate any guidance on resolving this issue!
Thank you.