I need help with validating the uniqueness of a username field in a form where an administrator can create a new user. I have implemented a uniqueUserNameValidator function for this purpose, but it always returns null. I suspect that the issue lies in the fact that the service used is asynchronous. How can I ensure that the async operation completes before proceeding? Adding an await statement seems to cause strange problems. Any guidance on resolving this would be greatly appreciated.
Below is where the validator is supposed to be applied:
this.userService.getEmployeeById(this.employeeId).subscribe(result => {
this.employee = result;
this.employeeDetailForm = new FormGroup({
userName: new FormControl(this.employee.userName, [Validators.required, this.uniqueUserNameValidator.bind(this)])
});
Here is the uniqueUserNameValidator implementation:
private uniqueUserNameValidator(control: FormControl): { [s: string]: boolean } {
this.employee.userName = control.value;
var userExists: boolean;
this.userService.checkIfEmployeeUserNameExists(this.employee).subscribe(data => {
userExists = data;
})
if (userExists) {
return { userExists: true };
}
return null;
}
And here is the relevant service method:
checkIfEmployeeUserNameExists(employee: Employee) {
return this.http.put<boolean>(this.baseUrl + 'employees/isUserNameUnique', employee)
}