Angular 5表单验证。检查现有的单词

时间:2018-04-18 18:57:44

标签: angular validation angular-forms angular-validation

我有一个输入的简单表单。

我需要检查用户是否输入了现有单词。

如果用户输入单词,我想在输入字段下方显示一条消息,如“此单词已存在!”。希望不使用反应形式 enter image description here

任何支持赞赏

import { Component, Inject } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";

@Component({
  selector: "app-tag-dialog",
  templateUrl: "./tag-dialog.component.html",
  styleUrls: ["../../styles/dialog.scss"]
})
export class TagDialogComponent {
  form: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private matDialogRef: MatDialogRef<TagDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.createForm();
  }

  createForm() {
    this.form = this.formBuilder.group({ tag: "" });
  }

  submit(form: any) {
    this.matDialogRef.close(form.value);
  }
}
<div class="dialog mat-typography">
  <h1 mat-dialog-title>{{ data.action }} tag</h1>
  <form [formGroup]="form" (ngSubmit)="submit(form)">
    <div mat-dialog-content>
      <div class="dialog__row">
        <mat-form-field class="dialog__input">
          <input matInput placeholder="Tag" formControlName="tag" required>
          <mat-error *ngIf="form.controls.tag.invalid">Tag is required</mat-error>
          <mat-error *ngIf=".............">This word already exists</mat-error>
        </mat-form-field>
      </div>
    </div>
    <div mat-dialog-actions class="dialog__row dialog__row--actions">
      <button mat-button type="reset" color="primary" mat-dialog-close>CANCEL</button>
      <button mat-button type="submit" color="primary" [disabled]="!form.valid">OK</button>
    </div>
  </form>
</div>

1 个答案:

答案 0 :(得分:2)

<强> tags.validator.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[tagValidator]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: TagsValidator,
    multi: true
  }]
})
export class TagsValidator implements Validator {
  @Input('tagValidator') tags: string[];

  validate(control: FormControl) {
    const hasTag = this.tags.indexOf(control.value) > -1;

    return hasTag
      ? { duplicateTags: true }
      : null;
  }
}

使用示例:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <input [(ngModel)]="tag" [tagValidator]="existingTags" #dir="ngModel" />
  <div> Valid: {{ dir.valid }} </div>
  <div> Existing tags: {{ existingTags | json }} </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  tag = 'hello';
  existingTags = ['hello', 'world'];
}

Live demo