Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular template-driven form-validation using a directive

Tags:

angular

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!

like image 854
Uğur Dinç Avatar asked May 29 '26 07:05

Uğur Dinç


1 Answers

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
  ....
}
like image 175
Eliseo Avatar answered May 31 '26 05:05

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!