问题描述
我有一个要通过多个验证器验证的字段。
使用模块驱动方法,代码看起来像这样:
I have a field I want to validate with multiple validators.
Using the Module Driven approach the code looks likes this:
this.exampleForm = this.fb.group({
date_start : ['', Validators.compose([
Validators.required,
Validators.pattern("[0-9]{2}-[0-9]{2}-[0-9]{4}")
])
]
})
但是我也可以不用 Validators.compose()这样写:
But I can also write this withouth Validators.compose() like:
this.exampleForm = this.fb.group({
date_start : ['', [
Validators.required,
Validators.pattern("[0-9]{2}-[0-9]{2}-[0-9]{4}")
]
]
})
而且效果很好。我个人更喜欢第二版(无需 compose ),更少的代码和更好的可读性。这就引出了一个问题,我为什么要使用Validators.compose()?
And it works just fine. Personally I prefer the 2nd version (without compose), less code and better readability. And this begs the question, why should I use Validators.compose()?
推荐答案
创建 new FormControl / FormGroup / FormArray
(AbstractControl)- coerceToValidator
被调用。
When we create new FormControl/FormGroup/FormArray
(AbstractControl) - coerceToValidator
is called.
function coerceToValidator(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): ValidatorFn|
null {
const validator =
(isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).validators :
validatorOrOpts) as ValidatorFn |
ValidatorFn[] | null;
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
export function composeValidators(validators: Array<Validator|Function>): ValidatorFn|null {
return validators != null ? Validators.compose(validators.map(normalizeValidator)) : null;
}
因此,在将验证器传递给AbstractControl之前,无需编写验证器。
So there is no need to compose validators before we pass it to an AbstractControl.
6/13/16添加了 feat(forms):如果是数组,则自动组成验证器fns
, Validators.compose是为了向后兼容。
6/13/16 was added feat(forms): compose validator fns automatically if arrays
from now on, Validators.compose is there for backward compatibility.
这篇关于为什么要使用Validators.compose()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!