angularformsangular-directivecustom-validators

angular 4 : custom validator not working


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>

Solution

  • your directive it's called appForbiddenName, so

    //in your directive
    @Input('appForbiddenName') forbiddenName: string;
    
    //In your template driven Form
    <input id="name" ...  appForbiddenName="bob" ...>