angular 4 : custom validator not working

时光怂恿深爱的人放手 提交于 2019-12-08 06:40:47

问题


I pulled this example from angular official doc. I noticed that the custom validation is working with the reactive forms but it is not working with template-driven forms.

Here is the plunker of the mentioned example

the directive:

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;
    }
  }

the template:

  <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>

回答1:


your directive it's called appForbiddenName, so

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

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


来源:https://stackoverflow.com/questions/47752444/angular-4-custom-validator-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!