SamS87
SamS87

Reputation: 41

Angular and async custom validation

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 ?

Upvotes: 0

Views: 550

Answers (1)

Vova Bilyachat
Vova Bilyachat

Reputation: 19484

You are returning object all the time.

To make it work you need to return object with key when you have error or null when its all good

 map(result => {  return result.success ? {invalidUsername: {value: control.value}} : null; })

Note i dont know what is result so result.success should be changed to.

Upvotes: 1

Related Questions