首页 > 解决方案 > 验证 mat-autocomplete 是对象

问题描述

我是 Angular 的新手。我有一个 html 表单:

   <form class="input-form" [formGroup]='terminalsForm'>
      <mat-form-field class="form-full-width">
        <input matInput placeholder="From" [matAutocomplete]="auto" formControlName='terminalInput' required>

      </mat-form-field>

      <span>Your choice is: {{terminalsForm.get('terminalInput').value | json}}</span>

      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
          <mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
            <span>{{ terminal.name }}, {{terminal.city}}</span>
          </mat-option>
      </mat-autocomplete>
    </form>

它工作正常,并且 span 指示我是否选择了一个对象(如果我自动编译对象,它会返回一个包含 id 的 json)。如何使用 select required 验证此字段?我接下来需要传递终端 ID,因此不选择应该是验证错误。谢谢!

标签: angular

解决方案


更新于 24-01-2019

根据@D 的评论。Make中需要自定义验证器功能input

所以,我更新了stackblitz上的代码。

我添加了一个名为 的新验证器forbiddenNamesValidator,它允许用户仅从建议的值中输入名称。它已被添加到myControl如下所示:

自动完成-简单-example.ts

...
constructor() {
    this.myControl.setValidators(forbiddenNamesValidator(this.options));
}
...
export function forbiddenNamesValidator(names: string[]): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    // below findIndex will check if control.value is equal to one of our options or not
    const index = names.findIndex(name => {
      return (new RegExp('\^' + name + '\$')).test(control.value);
    });
    return index < 0 ? { 'forbiddenNames': { value: control.value } } : null;
  };
}

html中的广告,处理如下:

...
<mat-error *ngIf="myControl.hasError('forbiddenNames')">
      You should enter value from suggested one only. <strong>'{{myControl.errors.forbiddenNames.value}}'</strong> is not allowed.
</mat-error>
...

原始答案

要处理验证错误,您必须将其附加到input[required]inside mat-form-field

<mat-form-field class="form-full-width">
    <input type="text" matInput placeholder="Terminals" formControlName="terminal" required [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let terminal of (filteredTerminals)?.results" [value]="terminal">
            <span>{{ terminal.name }}, {{terminal.city}}</span>
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

您还可以在stackblitz上查看 Angular Material Team 的官方示例。


推荐阅读