本文介绍了为什么要使用 Validators.compose()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段要使用多个验证器进行验证.
使用模块驱动方法,代码如下所示:

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): compose validator fns if arrays 从现在开始,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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 02:15