如何验证输入字段以接受 Angular 6 数组中的值

我有一个场景,其中输入字段中的 应该接受数组中存在的值。如果添加其他值,它应该抛出错误。

.component.html

<input type="text" ([ngModel])="InputValues" (blur)="validate()">

.component.ts

arrayList =  ['table_1', 'table_2', 'table_3', 'table_4'];

arrayList 有 4 个元素,输入字段应仅接受此值,如果输入任何其他值,则应抛出错误。输入应该接受 arrayList 中存在的值。


慕斯709654
浏览 156回答 3
3回答

RISEBY

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

潇潇雨雨

您可以通过从 Angular cli = (npm install lodash) 安装来使用 lodash 库validate() {&nbsp; &nbsp; let dataPresentOrNot = lodash.includes(this.arrayList,this.InputValues);&nbsp; &nbsp; if (dataPresentOrNot) {&nbsp; &nbsp; &nbsp; &nbsp;console.log("Entered Value is in Array List"); // success message&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp;console.log("Entered Value is not in Array List"); // Or any error message&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;document. getElementById('you need to pass id of input element here'). value = '' // you can clear out the text box entered value&nbsp; &nbsp; }&nbsp; }您可以使用 toastr 通知传递消息以获得良好的 ui 可见性,也可以使用 Angular Validators 方法来执行验证。

FFIVE

我们可以将自定义验证器添加到反应式表单中在 HTML 中<form [formGroup]="tableForm">&nbsp; &nbsp; <div class='form-group'>&nbsp; &nbsp; &nbsp; &nbsp; Table values<input id="tableValue" class='form-control' type="text" formControlName="tableValue" required><br>&nbsp; &nbsp; </div>&nbsp; &nbsp; <span style="color:red" *ngIf="tableForm.get('tableValue').errors?.inputValidator">Enter a valid value</span><br></form>在 ts 中&nbsp; title = "TableValues";&nbsp; tableForm: FormGroup;&nbsp; constructor(private fb: FormBuilder) { }&nbsp; ngOnInit() {&nbsp; &nbsp; // Basic FormControl&nbsp; &nbsp; this.tableForm = new FormGroup({&nbsp; &nbsp; &nbsp; tableValue: new FormControl(),&nbsp; &nbsp; });&nbsp; &nbsp; // FormBuilder example&nbsp; &nbsp; this.tableForm = this.fb.group({&nbsp; &nbsp; &nbsp; tableValue: [null, this.inputValidator(['x', 'y', 'z'])],&nbsp; &nbsp; });&nbsp; }&nbsp; inputValidator(val) {&nbsp; &nbsp; return (control: AbstractControl): { [key: string]: boolean } | null => {&nbsp; &nbsp; &nbsp; if (&nbsp; &nbsp; &nbsp; &nbsp; control.value !== null && !val.includes(control.value)&nbsp; &nbsp; &nbsp; ) {&nbsp; &nbsp; &nbsp; &nbsp; return { inputValidator: true };&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; };&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript