3 回答

TA貢獻1856條經驗 獲得超5個贊
validate() {
? this.displayMessage = '';
? const arrayList = ['table_1', 'table_2', 'table_3', 'table_4'];
? if (arrayList.indexOf(this.InputValues) > 0) {
? ? this.displayMessage = "Entered Value is in the Array List";
? } else {
? ? this.displayMessage = "Entered Value is not in the Array List";
? }
}
<input type="text" ([ngModel])="InputValues" (blur)="validate()">
<span *ngIf='displayMessage'></span>
注意:- 您可以使用核心 javascript 檢查數組是否包含值。indexOf()、includes()方法。

TA貢獻1833條經驗 獲得超4個贊
您可以通過從 Angular cli = (npm install lodash) 安裝來使用 lodash 庫
validate() {
let dataPresentOrNot = lodash.includes(this.arrayList,this.InputValues);
if (dataPresentOrNot) {
console.log("Entered Value is in Array List"); // success message
} else {
console.log("Entered Value is not in Array List"); // Or any error message
document. getElementById('you need to pass id of input element here'). value = '' // you can clear out the text box entered value
}
}
您可以使用 toastr 通知傳遞消息以獲得良好的 ui 可見性,也可以使用 Angular Validators 方法來執行驗證。

TA貢獻1797條經驗 獲得超6個贊
我們可以將自定義驗證器添加到反應式表單中
在 HTML 中
<form [formGroup]="tableForm">
<div class='form-group'>
Table values<input id="tableValue" class='form-control' type="text" formControlName="tableValue" required><br>
</div>
<span style="color:red" *ngIf="tableForm.get('tableValue').errors?.inputValidator">Enter a valid value</span><br>
</form>
在 ts 中
title = "TableValues";
tableForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
// Basic FormControl
this.tableForm = new FormGroup({
tableValue: new FormControl(),
});
// FormBuilder example
this.tableForm = this.fb.group({
tableValue: [null, this.inputValidator(['x', 'y', 'z'])],
});
}
inputValidator(val) {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (
control.value !== null && !val.includes(control.value)
) {
return { inputValidator: true };
}
return null;
};
}
添加回答
舉報