angular 4:自定义验证器不工作

angular 4 : custom validator not working

我从 angular 官方文档中提取了这个例子。我注意到自定义验证适用于反应式表单,但不适用于模板驱动的表单。

这是 mentioned example

的插件

指令:

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>

你的指令叫做 appForbiddenName,所以

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

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