0

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

.component.html

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

.component.ts

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

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

4

3 回答 3

1

您可以通过从 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 方法执行验证。

于 2020-12-10T06:38:00.000 回答
0

我们可以将自定义验证器添加到响应式表单

在 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;
    };
  }
于 2020-12-10T15:26:31.187 回答
0

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

于 2020-12-10T06:47:00.167 回答