3

I've been checking out the form validation fundamentals at the official docs and I can't wrap my head around with one of the examples.

Some background:

In this sample, the forbidden name is "bob", so the validator will reject any hero name containing "bob". Elsewhere it could reject "alice" or any name that the configuring regular expression matches.

And here is the input element:

<input id="name" name="name" class="form-control"
   required minlength="4" forbiddenName="bob"
   [(ngModel)]="hero.name" #name="ngModel" >

Yet, the input from their example seems to be not validated:

enter image description here

while the input using reactive forms from the same example gets validated as expected:

enter image description here

How do I make template-driven form display the alert as seen in reactive form?

Here is the example from the official docs: https://stackblitz.com/angular/byyynkdrode

Thanks in advance!

1 Answer 1

3

Must be

<input id="name" name="name" class="form-control"
               required minlength="4" appForbiddenName forbiddenName="bob"
               [(ngModel)]="hero.name" #name="ngModel" >

or

<input id="name" name="name" class="form-control"
               required minlength="4" appForbiddenName [forbiddenName]="'bob'"
               [(ngModel)]="hero.name" #name="ngModel" >

See that the directive name is "appForbiddenName" and the @Input variable is "forbiddenName". Of course you can change the directive, and make that name of the selector was the same that the @Input

@Directive({
  selector: '[forbiddenName]', //<--forbiddenName, NOT appforbiddenName
  providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
  @Input() forbiddenName: string; //<--see that the input variable is the same
                                  //that the selector of the directive
  ....
}
Sign up to request clarification or add additional context in comments.

1 Comment

Figured it out 5mins ago and I was about to answer it on my own. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.