我想在FormGroup中为用户可以为其DOB选择的最小和最大日期创建自定义验证器,最小日期为1900年1月1日,最大日期为当前日期。这是我当前的代码:
export class CustomValidators {
static dateMinimum(mindate: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null) {
return null;
}
const controlDate = moment(control.value, '01/01/1990');
if (!controlDate.isValid()) {
return null;
}
const validationDate = moment(mindate);
return controlDate.isBefore(validationDate) ? null : {
'date-minimum': {
'date-minimum': validationDate.format('01/01/1990'),
'actuel': controlDate.format('01/01/1990')
}
};
};
}
static dateMaximum(maxdate: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null) {
return null;
}
const controlDate = moment(control.value, '');
if (!controlDate.isValid()) {
return null;
}
const validationDate = moment(maxdate);
return controlDate.isAfter(validationDate) ? null : {
'date-maximum': {
'date-maximum': validationDate.format(''),
'actuel': controlDate.format('')
}
};
};
}
}
export class PersonalInfoComponent implements OnInit {
peopleCoveredDOBs = new FormControl('', [Validators.required, CustomValidators.dateMaxmimum(''), CustomValidators.dateMinimum('1900-0-1')])
startDate = new FormControl('', Validators.required)
numCovered = new FormControl('', [Validators.required, Validators.max(8)])
selfCovered = new FormControl('', Validators.required)
ZIPCode = new FormControl('', [Validators.required, Validators.minLength(5), Validators.maxLength(5)])
personalInfoForm: FormGroup = this.builder.group({
peopleCoveredDOBs: this.peopleCoveredDOBs,
startDate: this.startDate,
numCovered: this.numCovered,
selfCovered: this.selfCovered,
ZIPCode: this.ZIPCode
});
}
当前,dateMaximum wavlidator没有传递到窗体控件中。有没有更简单的方法来添加多个静态自定义验证器?我还想使用我的公共badZIPSubmitted = false;为邮政编码添加一个自定义验证器;