【问题标题】:Angular 5 form validation. to check existing wordAngular 5 表单验证。检查现有单词
【发布时间】:2018-09-29 03:11:50
【问题描述】:

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

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

如果用户输入单词,我想在输入字段下方显示一条消息,例如“该单词已存在!”。最好不要使用反应形式

感谢任何支持

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>

【问题讨论】:

  • 你有一些现有单词的列表,用来比较提供的单词吗?

标签: angular validation angular-forms angular-validation


【解决方案1】:

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

【讨论】:

  • 你能告诉我如何在模板驱动的表单中使用它吗?还是有其他方法可以做同样的事情?
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多