Validators.compose方法应该可以完成工作,例如:
let formControls = {
'oldPassword': new FormControl({ value: ''}),
'newPassword': new FormControl({ value: ''}, Validators.compose([customValidator1, customValidator2]), customAsyncValidator)
};
组合验证器同时工作,这意味着我们可以同时在控件上出现多个错误(如果验证失败,每个验证器都会附加自己的错误)。如果我们一次只需要在控件上出现一个错误,我们可以通过在执行下一个验证之前检查前一个验证的状态来“链接”验证器。像这样的东西:
let customValidator2 = (ctrl: FormControl): any => {
if(ctrl.hasError('customValidationError1')) {
// there is the error attached by customValidator1,
// skip executing customValidator2 (nullify its error)
return null;
}
let isInvalid = true; // some condition...
return isInvalid ? { customValidationError2: true } : null;
}
通过这种方式,我们可以通过验证器的优先级来完成“排序”。