当您想要实现包含一个或多个同级(表单)控件的验证时,您必须在同级控件的上一级/之上定义验证器函数。例如:
ngOnInit() {
this.form = this.formbuilder.group({
'startDate': ['', [<control-specific - validations >]],
'endDate': ['', [<control-specific - validations >]]
}, { validator: checkIfEndDateAfterStartDate });
}
然后在组件类的定义之外(在同一个文件中),同样定义函数checkIfEndDateAfterStartDate。
export function checkIfEndDateAfterStartDate (c: AbstractControl) {
//safety check
if (!c.get('startDate').value || !c.get('endDate').value) { return null }
// carry out the actual date checks here for is-endDate-after-startDate
// if valid, return null,
// if invalid, return an error object (any arbitrary name), like, return { invalidEndDate: true }
// make sure it always returns a 'null' for valid or non-relevant cases, and a 'non-null' object for when an error should be raised on the formGroup
}
通过将错误标志(此处为invalidEndDate)添加到true 到该FormGroup 的错误对象,此验证将使FormGroup 无效。如果您想在任何同级控件上设置特定错误,则可以使用c.get('endDate').setErrors({ invalidEndDate: true }) 之类的东西手动设置formControl 上的错误标志。如果您这样做,请确保通过将错误设置为 null 来清除它们的有效大小写,例如 c.get('endDate').setErrors(null)。
可以看到类似验证的现场演示here。