2727
2727

Reputation: 49

Custom validator in template driven form always returns null

I am trying to add custom validator in template driven form. I am using Angular 7. Whatever be the value, I am always getting null.

HTML:

<div class="form-group">
  <label style="font-weight:bold">Seats Available</label> <input type="number" required class="form-control" [(ngModel)]="seats" name="carseat" #carseat="ngModel" validateseat />
  <div *ngIf="carseat.dirty && carseat.errors?.validseat">Required.</div>
</div>

Code:

import { Validator, FormControl } from "@angular/forms";
import { Directive } from "@angular/core";

@Directive({
  selector: "[validateseat]"
})
export class Seatvalidatordirective implements Validator {
  validate(control: FormControl): { [key: string]: any } | null {
    console.log("dd", control.value);
    return control.value < 0 || control.value > 8 ? { validseat: true } : null;
  }
}

Upvotes: 2

Views: 650

Answers (1)

AVJT82
AVJT82

Reputation: 73357

You are not actually providing your custom validator, you need to add:

providers: [
  { provide: NG_VALIDATORS, useExisting: Seatvalidatordirective, multi: true }
]

to your directive:

@Directive({
  selector: "[validateseat]",
  providers: [
    { provide: NG_VALIDATORS, useExisting: Seatvalidatordirective, multi: true }
  ]
})
export class Seatvalidatordirective implements Validator {
  validate(control: FormControl): { [key: string]: any } | null {
    console.log("dd", control.value);
    return control.value < 0 || control.value > 8 ? { validseat: true } : null;
  }
}

Here's a StackBlitz

Upvotes: 1

Related Questions