Reputation: 49
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
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