我正在尝试以模板驱动形式添加自定义验证器。我正在使用Angular7。无论值是多少,我总是得到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>
代码:
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;
}
}
答案 0 :(得分:0)
您实际上并未提供自定义验证程序,需要添加:
providers: [
{ provide: NG_VALIDATORS, useExisting: Seatvalidatordirective, multi: true }
]
您的指令:
@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;
}
}
这里是 StackBlitz