1
在我的Angular 2和材質應用程序中,我想檢查用戶名是否已經被使用。如果它已經被採用,那麼它應該顯示錯誤。Angular2材質:對角度材質輸入的自定義驗證
我在下面的指南。
https://material.angular.io/components/input/overview#error-messages
打字稿文件
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>
也許看看這篇文章https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html? –
你是否設法讓它工作?如果是的話,你可以分享你的解決方案。 – jowey