I need to check in my app if a username is already taken and check with my backend. To make this as easy as possible instead of doing a on blur function call on the input control i opted to use a async custom validator.
My Validator looks like this.
export function userNameValidator(userservice: UserService): AsyncValidatorFn {
return (control: AbstractControl) => {
return userservice.validateUsername(control.value.toLowerCase())
.pipe(
tap(result => console.log(result)),
// tslint:disable-next-line: semicolon
// tslint:disable-next-line: arrow-return-shorthand
map(result => { return result; })
);};}
Where the returned result looks like this {username_avail: true}
And here is how i register the custom async validator
form = this.fb.group({
username: ['', {
validators: [
Validators.required,
Validators.minLength(5),
Validators.maxLength(20)
],
asyncValidators: [userNameValidator(this.userservice)],
updateOn: 'blur'
}]});
I can see that my system hits the validator and makes the back end call but for some reason i cant get it to work. Is there a way to to tell the system what a valid response is or does it always have to be null ?