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.
I am following below guide.
https://material.angular.io/components/input/overview#error-messages
Typescript file
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 => {
if(object.attributeClass === this.attributeClass) {
console.log("found " + JSON.stringify(object));
return true;
}
});
return false;
}
}
HTML
<form class="example-form">
<md-form-field class="example-full-width">
<input mdInput placeholder="Email [formControl]="emailFormControl">
<md-error *ngIf="emailFormControl.hasError('required')">
Email is <strong>required</strong>
</md-error>
<!-- I want to make something like that - custom validation -->
<md-error *ngIf="emailFormControl.hasError('username-already-taken')">
Username is already taken. Please try another.
</md-error>
<!-- custom validation end -->
</md-form-field>