我有一个自定义验证器来评估2个控制器值; totalDisch应该超过damaNumb
组件文件:
form = new FormGroup({
hospital: new FormControl({ value: '', disabled: true }, Validators.required),
department: new FormControl('', Validators.required),
damaDt: new FormControl('', Validators.required),
damaNumb: new FormControl('', Validators.required),
totalDisch: new FormControl('', Validators.required),
notes: new FormControl('', Validators.maxLength(125))
}, invalidDama);
同一文件中的自定义验证程序
export function invalidDama(c: AbstractControl) {
//safety check
if (!c.get('damaNumb').value || !c.get('totalDisch').value) {
return {c: c.get('totalDisch').setErrors(null)};
}
if (c.get('damaNumb').value < c.get('totalDisch').value) {
return {c: c.get('totalDisch').setErrors(null)};
}
return {c: c.get('totalDisch').setErrors({invalidDama: true})};
}
html模板
<div class="form-group">
<label for="damaNumb">DAMA Number:</label>
<input type="number" formControlName="damaNumb" id="damaNumb" class="form-control" placeholder="Enter DAMA Number (1-100)" [(ngModel)]="damaNumb" [min]="1" [max]="100" />
<div *ngIf="form.get('damaNumb').touched && form.get('damaNumb').invalid" class="alert alert-danger">
<div *ngIf="form.get('damaNumb').errors.required">DAMA Number is required....</div>
<div *ngIf="form.get('damaNumb').errors.min">Minimum "1"....</div>
<div *ngIf="form.get('damaNumb').errors.max">Maximum "100"....</div>
</div>
</div>
<div class="form-group">
<label for="totalDisch">Total Discharges:</label>
<input type="number" formControlName="totalDisch" id="totalDisch" class="form-control" placeholder="Enter Total Discharges (1-100)" [(ngModel)]="totalDisch" [min]="1" [max]="100" />
<div *ngIf="form.get('totalDisch').touched && form.get('totalDisch').invalid" class="alert alert-danger">
<div *ngIf="form.get('totalDisch').errors.required">Total Discharges is required....</div>
<div *ngIf="form.get('totalDisch').errors.min">Minimum "1"....</div>
<div *ngIf="form.get('totalDisch').errors.max">Maximum "100"....</div>
<div *ngIf="form.get('totalDisch').errors.invalidDama">Discharges can not be less than DAMA....</div>
</div>
</div>
验证器按预期工作但是 页面提交但在控制台表单中始终无效且错误
控制台错误
_errors:c:undefined
有任何帮助吗? 提前谢谢............
答案 0 :(得分:0)
您需要在相应的Form元素中定义自定义验证器。
totalDisch: new FormControl('',[Validators.required,invalidDama(input val or regex)]),
答案 1 :(得分:0)
您的验证器应如下所示:
const ageValidator: ValidatorFn = (fg: FormGroup) => {
const damaNumb = fg.get('damaNumb').value;
const totalDisch = fg.get('totalDisch').value;
if (totalDisch > damaNumb ) {
return null;
}
fg.get('totalDisch').markAsTouched();
fg.get('totalDisch').setErrors({ invalidDama: true });
return { invalidDama: true };
};
由于它是fg级验证器,因此返回将是fg级错误。如果您想要特定控件上的其他错误,则必须使用本示例中的setErrors进行设置。