我编写了一个自定义验证器,以从表单组中获取2个日期值并进行比较。看来,当此验证程序运行时,逻辑所需的最后一个值在逻辑尝试运行之前未及时更新。
我已经用console.log'd整个验证程序尝试查找问题,看来问题出在检查所需的最后一个值的有效性。
自定义验证程序:
// Validate Effective Date Vs. Termination Date
valEffDateTermDate(c: AbstractControl): { [key: string]: boolean } | null {
let effDate = c.get('effectiveDate').value;
let termDate = c.get('terminationDate').value;
let dateRegex = /(?:0[1-9]|[1-2][0-9]|3[0-1])\/(?:0[1-9]|1[0-2])\/(?:19\d\d|20\d\d|99\d\d)/g;
let isValidEffDate = dateRegex.test(effDate);
let isValidTermDate = dateRegex.test(termDate);
if (effDate.length === 10 && termDate.length === 10 && isValidEffDate === true && isValidTermDate === true) {
console.log('Initial Criteria Met');
if (new Date(effDate).toISOString() >= new Date(termDate).toISOString()) {
console.log('Setting effDateTermDate to true');
return { effDateTermDate: true};
}
return null;
}
return null;
}
FormBuilder设置:
// Angular FormBuilder Construction and Initialization
this.createCodeForm = this.fb.group({
codeName: ['', [ Validators.required,
Validators.pattern('^[a-zA-Z0-9]*$'),
this.v.valCodeName(this.selectedDisplayedName) ]],
codeSetName: this.selectedCSName,
codeSubSetName: this.selectedCSSubName,
createCodeDates: this.fb.group({
effectiveDate: ['', [ Validators.required,
this.v.valDate,
this.v.valEffDateCSEffDate(this.selectedEffDate)
]],
terminationDate: ['', [ Validators.required,
this.v.valDate,
this.v.valTermDateCSTermDate(this.selectedTermDate)]],
systemEffectiveDate: ['', [ Validators.required,
this.v.valDate,
this.v.valSysEffDateCSSysEffDate(this.selectedSysEffDate)]],
systemTerminationDate: ['', [ Validators.required,
this.v.valDate,
this.v.valSysTermDateCSSysTermDate(this.selectedSysTermDate)]],
}, { validator: Validators.compose([this.v.valEffDateTermDate,
this.v.valEffDateSysTermDate,
this.v.valTermDateSysTermDate,
this.v.valSysEffDateSysTermDate])}
),
typeCode: '',
classification: '',
subClassification: '',
copayCode: ['' , [ this.v.valCopayCode(this.selectedDisplayedName) ]],
shortDescription: ['', [Validators.required, Validators.maxLength(100)]],
longDescription: ['', [Validators.required, Validators.maxLength(500)]],
comments: ['', [Validators.maxLength(300)]]
});
}
预期结果是让valEffDateTermDate在有效日期和termDate的长度=== 10之后运行,并且对每个正则表达式均有效。没有错误发生,已经输入了有效日期后,在为termDate输入第10个字符后逻辑就不会运行。
请注意,如果我取消对isValidTermDate === true的检查,则逻辑将运行,一旦添加回逻辑中,则该逻辑甚至不会运行。