Custom validator with dependency


#1

I have a simple form, with three inputs - username, password, password2. I want to check if username isnt already taken, so i created custom validator, but it doesnt seems to work. Any ideas?

<form [formGroup]="form">
    <ion-list>
        <ion-item>
          <ion-label floating>Uživatelské jméno</ion-label>
          <ion-input formControlName="username" type="text"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label floating>Heslo</ion-label>
          <ion-input formControlName="password" type="password"></ion-input>
        </ion-item>
        <ion-item>
          <ion-label floating>Heslo znovu</ion-label>
          <ion-input formControlName="password2" type="password" ></ion-input>
        </ion-item>
      <ion-item>
        <button [disabled]="!form.valid" (click)="dismiss('save')" ion-button block>Přidat admina</button>
      </ion-item>
    </ion-list>
  </form>
export class AddAdminModal{
  form;
  username;
  password;
  password2;

  constructor(public navParams:NavParams,public viewCtrl:ViewController, public fb:FormBuilder,private userService:UserService) {
    this.form = this.fb.group({
      "username": ["",(control)=>this.validateUsername(control)],
      "password": ["",],
      "password2": ["", Validators.required]
    }, {'validator': PasswordValidator.isMatching});
    console.log('pokus123');
    console.log(this.userService.admins);
  }





  dismiss(mode:string=null){
    if(mode=='save'){
      let admin={
        username:this.form.controls["username"].value,
        password:this.form.controls["password"].value,
        password2:this.form.controls["password2"].value
      };
      this.viewCtrl.dismiss(admin);
    }
    else{
      this.viewCtrl.dismiss();
    }
  }

  validateUsername(control:AbstractControl){
    this.userService.admins.forEach((admin)=>{
      if(control.value==admin.username){
      console.log('Username taken');
        return {'usernameTaken':true}
      }
    });
    return null;

  }

It logs username taken, when the admin username is already taken, but it doesnt make the form invalid. How can i fix this?