title: Custom Validator Angular 2
body: <p>I've written a web api function that takes a username from the textfield and checks if the username is already taken. To know if the username is available or not, my server returns <code>Y</code> if it is available and <code>N</code> if its not. </p>
  
  <p>To validate the username, I'm using a ValidatorFn in Angular2 so validate the input. However, my validator function is not working. </p>
  
  <p>Here is the validator function:</p>
  
  <pre><code>interface Validator&lt;T extends FormControl&gt; {
    (c: T): { [error: string]: any };
  }
  
  function validateUsername(c: string) : ValidatorFn {
    return (this.isAvailable(c)=='Y') ? null : {
      validateUsername: {
        valid: false
      }
    };
  }
  </code></pre>
  
  <p>Here is the isAvailable function:</p>
  
  <pre><code>private isAvailable(username: string) {
    let usernameAvailable;
    let url = 'URL/api/auth/checkuser/' + username;
    let headers = new Headers();
    headers.append('User', sessionStorage.getItem('username'));
    headers.append('Token', sessionStorage.getItem('token'));
    headers.append('AccessTime', sessionStorage.getItem('AccessTime'));
  
    let options = new RequestOptions({ headers: headers });
  
    this.http.get(url, options)
      .subscribe((res: Response) =&gt; usernameAvailable);
    return usernameAvailable; //returns Y or N
  }
  </code></pre>
  
  <p>Form Builder:</p>
  
  <pre><code>complexForm: FormGroup;
  constructor(private http: Http, fb: FormBuilder) {
  
    this.complexForm = fb.group({
      'username': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10), validateUsername(this.complexForm.controls['username'].value)])],
    })
  }
  </code></pre>
  
  <p><code>validateUsername(this.complexForm.controls['username'].value)</code> is failing and I'm getting this error:</p>
  
  <pre><code>[ts] Type '{ validateUsername: { valid: boolean; }; }' is not assignable to type 'ValidatorFn'.   Object literal may only specify known properties, and 'validateUsername' does not exist in type 'ValidatorFn'. (property) validateUsername: {
      valid: boolean;
  }
  </code></pre>