[英]Conditional custom validation of reactive form not working - Angular 9
我肯定错过了什么:
<input
formControlName="endDate"
type="date"
id="endDate"
class="form-control"
(change)="onDateChange()"
required
/>
<div *ngIf = "timesheetForm.get('endDate').errors?.invalidEndDate">
<small class="text-danger"> TTTT</small></div>
还有.ts
this.timesheetForm = this.fb.group({
endDate: ["", DateValidators.invalidEndDate],
}, {
validator: DateValidators.invalidEndDate
});
const endDateControl = this.timesheetForm.get('endDate');
endDateControl.valueChanges.subscribe((value) => {
if (value) {
this.timesheetForm.get('endDate').setValidators([DateValidators.invalidEndDate]);
} else {
this.timesheetForm.get('endDate').clearValidators();
}
});
这是我的自定义验证器
export class DateValidators {
static invalidEndDate(formGroup: FormGroup): ValidationErrors | null {
let startDateTimestamp: number;
let endDateTimestamp: number;
for (const controlName in formGroup.controls) {
if (controlName.indexOf("startDate") !== -1) {
startDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
if (controlName.indexOf("endDate") !== -1) {
endDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
}
return (endDateTimestamp < startDateTimestamp) ? { invalidEndDate : true} : null;
}
它返回 invalidEndDate:true,因此验证按预期工作,但我无法正确显示错误消息。
ValidatorFn 接口
function 接收控制并同步返回验证错误的 map(如果存在),否则返回 null。
基于 angular.io文档:
interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}
您必须在验证器构造函数中使用 control 而不是 formGroup。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.