如何在Angular 9中使用自定义验证器

时间:2020-06-19 07:55:13

标签: angular angular-forms

我正在尝试在Angular 9中实现自定义验证器。

这是我的验证器(不完整,只是在输入'aaaa'的情况下试图使它失败)。

import { AbstractControl, ValidationErrors } from '@angular/forms';

export class ManufactureCodeValidator {
  static mustBeHex(control: AbstractControl): ValidationErrors | null {
    if (control.value == 'aaaa') {

      return {mustBeHex: true}
    }
    return null;
  }
}

然后在与我的html组件相关联的组件文件中:

import { NgForm, Validators } from "@angular/forms";
import { ManufactureCodeValidator } from '../../../validators/manufacturecode';

@Component({
  selector: 'maintain-manufacturers',
  providers: [Title],
  templateUrl: './maintain-manufacturers.component.html',
  styleUrls: ['../../shared/form/form-styles.css']
})

export class MaintainManufacturersComponent implements OnInit {
  @ViewChild(ActionSubmissionModal) submittingModal: ActionSubmissionModal;
  @ViewChild('manufacturerForm') form: NgForm;

........
 ngOnInit(): void {
      this.title = 'Maintain Manufacturers';
      this.titleService.setTitle(this.title);

      this.form = new NgForm(null, [ManufactureCodeValidator]);
    }
......

然后在我的html模板中,我有:

<form (ngSubmit)="submit()" #manufacturerForm="ngForm">
  <fieldset class="form-area">
    <legend>Maintain Manufacturer</legend>
    <div class="form-group form-inline row">
      <div class="col-md-2">
        <label class="pull-right" for="code">Manufacturer Code</label>
      </div>
      <div class="col-md-2">
        <input class="form-component-with-input" [(ngModel)]="request.code" [value]="request.code" maxlength="4" name="code" id="code" ManufactureCodeValidator.mustBeHex (onblur)="codeChanged($event)" required  />
      </div>
      <div class="col-md-2">
        <validation-message [control]="code" [message]="'Manufacturer Code must be a hexadecimal value of excactly 4 characters'"></validation-message>
      </div>
......

所以我想看的是,如果我在输入框中输入“ aaaa”,当它失去焦点时,应该出现我的验证消息。我究竟做错了什么?

0 个答案:

没有答案