0

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 ?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so basically when ever my custom validator validates and it passes i should return a null
@SamS87 you should return null only if value is valid :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.