亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何驗證輸入字段以接受 Angular 6 數組中的值

如何驗證輸入字段以接受 Angular 6 數組中的值

慕斯709654 2023-11-11 16:11:35
我有一個場景,其中輸入字段中的 應該接受數組中存在的值。如果添加其他值,它應該拋出錯誤。.component.html<input type="text" ([ngModel])="InputValues" (blur)="validate()">.component.tsarrayList =  ['table_1', 'table_2', 'table_3', 'table_4'];arrayList 有 4 個元素,輸入字段應僅接受此值,如果輸入任何其他值,則應拋出錯誤。輸入應該接受 arrayList 中存在的值。
查看完整描述

3 回答

?
RISEBY

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()方法。



查看完整回答
反對 回復 2023-11-11
?
瀟瀟雨雨

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 方法來執行驗證。


查看完整回答
反對 回復 2023-11-11
?
FFIVE

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;

    };

  }


查看完整回答
反對 回復 2023-11-11
  • 3 回答
  • 0 關注
  • 196 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號