title: Angular2 Material : Custom Validation for Angular Material Input
body: <p>In my Angular 2 and material application, I want to check whether username has already taken or not. If it is already taken then it should show the error.</p>
  
  <p>I am following below guide.<br>
  <a href="https://material.angular.io/components/input/overview#error-messages" rel="nofollow noreferrer">https://material.angular.io/components/input/overview#error-messages</a> </p>
  
  <p><strong>Typescript file</strong></p>
  
  <pre><code>import {Component} from '@angular/core';
  import {FormControl, Validators} from '@angular/forms';
  
  const existingUserNames = ['rohit', 'mohit', 'ronit'];
  
  @Component({
     selector: 'input-errors-example',
     templateUrl: 'input-errors-example.html',
     styleUrls: ['input-errors-example.css'],
  })
  export class InputErrorsExample {
  
      emailFormControl = new FormControl('', [
           Validators.required
      ]
  
      // I want to call below isUserNameTaken function but dont know 
      // how to use it with Validators so that error message will be visible.
  
      isUserNameTaken() : boolean {
         this.attributeClasses = attributeClasseses;
         this.attributeClasses.find( object =&gt; {
             if(object.attributeClass === this.attributeClass) {
                 console.log("found " + JSON.stringify(object));
                 return true;
             }
         });
         return false;
     }
  }
  </code></pre>
  
  <p><strong>HTML</strong></p>
  
  <pre><code> &lt;form class="example-form"&gt;
     &lt;md-form-field class="example-full-width"&gt;
       &lt;input mdInput placeholder="Email [formControl]="emailFormControl"&gt;
      &lt;md-error *ngIf="emailFormControl.hasError('required')"&gt;
        Email is &lt;strong&gt;required&lt;/strong&gt;
      &lt;/md-error&gt;
  
    &lt;!-- I want to make something like that - custom validation --&gt;
  
       &lt;md-error *ngIf="emailFormControl.hasError('username-already-taken')"&gt;
          Username is already taken. Please try another.
      &lt;/md-error&gt;
    &lt;!-- custom validation end --&gt;        
  
       &lt;/md-form-field&gt;
  </code></pre>
  
  <p></p>