Services in Form validation


#1

Can anyone share any working example of this. I am trying to call a service asncronously in the form validation. No matter what I do I am unable to call it and Ionic is showing bizarre errors.

Below is non-working sample of what I am trying.

this.signupForm = formBuilder.group({ username: ['',Validators.compose([Validators.required,Validators.maxLength(30), Validators.pattern(/[a-zA-Z0-9_]+/)],UsernameValidator.checkUsername), ],

in the validator

`
import { FormControl } from ‘@angular/forms’;

import { AuthenticationService } from ‘…/services/authentication’;

export class UsernameValidator {

static auth: AuthenticationService;
constructor(public auth:AuthenticationService){
}

static checkUsername(control: FormControl): any {
return new Promise(resolve => {
this.auth.checkUsernameAvailability(control.value). then((answer) => { <— This.auth is not defined !!!
if(answer[‘status’] == false) {
resolve({
“usernameTaken”: true
});
}
else {
resolve(null);
}

  }, (error) => {
    console.log("server problem");
    resolve({
        "ServerUnavailable": true
    });
  })
});  }}`

#2

Please edit your post and use the </> button above the post input field to format your code or error message or wrap it in ``` (“code fences”) manually. This will make sure your text is readable and if it recognizes the programming language it also automatically adds code syntax highlighting. Thanks.