Angular 4:自定义验证器无效[英] angular 4 : custom validator not working

本文是小编为大家收集整理的关于Angular 4:自定义验证器无效的处理方法,想解了Angular 4:自定义验证器无效的问题怎么解决?Angular 4:自定义验证器无效问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我从 Angular 官方Doc中.我注意到自定义验证正在使用反应形式,但它无法使用模板驱动的形式.

这是提到的例子

指令:

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      const forbidden = nameRe.test(control.value);
      return forbidden ? {'forbiddenName': {value: control.value}} : null;
    };
  }

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

    validate(control: AbstractControl): {[key: string]: any} {
      return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)
                                : null;
    }
  }

模板:

  <form #heroForm="ngForm">
      <div [hidden]="heroForm.submitted">

        <div class="form-group">
          <label for="name">Name</label>
          <input id="name" name="name" class="form-control"
                 required minlength="2" forbiddenName="bob"
                 [(ngModel)]="hero.name" #name="ngModel" >

          <div *ngIf="name.invalid && (name.dirty || name.touched)"
               class="alert alert-danger">

            <div *ngIf="name.errors.required">
              Name is required.
            </div>
            <div *ngIf="name.errors.minlength">
              Name must be at least 2 characters long.
            </div>
            <div *ngIf="name.errors.forbiddenName">
              Name cannot be Bob.
            </div>

          </div>
        </div>
      </div>
    </form>

推荐答案

您的指令它被称为apporbiddenname,因此

//in your directive
@Input('appForbiddenName') forbiddenName: string;

//In your template driven Form
<input id="name" ...  appForbiddenName="bob" ...>

本文地址:https://www.itbaoku.cn/post/1793776.html