验证垫自动完成是对象

时间:2019-01-23 13:08:52

标签: angular

我是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)。如何通过选择必填项来验证此字段?接下来,我需要传递终端ID,因此未选择应该是验证错误。谢谢!

2 个答案:

答案 0 :(得分:1)

已于2019年1月24日更新

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

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

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

autocomplete-simple-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]内的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的官方示例。

答案 1 :(得分:0)

在我的情况下,我的自动完成功能是从服务器端(对象数组)获取数据的,所以我创建了这个简单的函数来验证所选值是一个对象并且不同于null,这对我来说已经足够了。

我希望这对某人有用。

export function forbiddenObjectValidator(control: AbstractControl) {
        return typeof control.value !== 'object' || control.value === null ? { 'forbiddenObject': true } : null;
}