1

我的应用程序上有一个自定义组件继承了 ControlValueAccessor,它集成了ng-select

这个组件的目标是有一个集成 ng-select 的中心位置,以便我可以在整个应用程序中重复使用它。

这就是我调用验证方法的方式:

  constructor(
    @Optional() @Self() public controlDir: NgControl
  ) {
    controlDir.valueAccessor = this;
  }

  ngOnInit() {
    const control = this.controlDir.control;
    if (control.validator) {
      control.setValidators([this.validate.bind(this, [control.validator])]);
    }
    control.updateValueAndValidity({ emitEvent: false });
  }

  validate(validators: ValidatorFn[], c: FormControl) {
    const allErrors: any = {};
    for (const validator of validators) {
      const hasError = validator(c);
      if (hasError) {
        Object.entries(hasError).forEach(([errorName, isOnError]) => {
          allErrors[errorName] = isOnError;
        });
      }
    }

    if (Object.keys(allErrors).length > 0) {
      return allErrors;
    }

    return null;
  }

这就是我通常在父组件上实例化 formControl 的方式:

const control = this.formBuilder.control(['test@gmail.com'], [Validators.email]);

this.form = this.formBuilder.group({ test: control });

我想为父级提供在我的自定义组件上使用内置角度验证器的选项。(必填,电子邮件,最小,最大...)。

问题是我的自定义组件的控件值是一个字符串数组,例如该值将是:

[ 'test@gmail.com', 'jeff@gmail.com' ]

组件看起来像这样

组件截图

问题:在我的验证函数中,我可以访问 ValidatorFn 来检查我的控件是否是有效的电子邮件。如果我的控制值是一个字符串,它会按预期工作,但它是一个字符串数组,所以它不起作用。

所以我的猜测是我需要为我的自定义组件重新实现电子邮件验证器(因为 Angular 无法神奇地找出我的自定义组件中的数据结构是有道理的)。

但我不知道如何识别定义的验证器是Validator.email.

this.controlDir.control.validator是一个函数,我不知道如何识别它是电子邮件验证器,因此我可以为电子邮件添加自定义验证。

问题:我如何从我的自定义验证函数中知道哪个验证器是从父级设置的?是 Validators.required、Validators.email ...等吗

4

2 回答 2

1

我如何从我的自定义验证函数中知道哪个验证器是从父级设置的?

不幸的是,没有办法获得给定控件的验证器(详细信息)。

理论上,您可以迭代您的控制值(如果它是一个数组)并创建一个新FormControl的来验证数组中的每个字符串。

作为一个例子,你可以这样做:

isControlValid(controlValue: string[], validator: ValidatorFn) {
  let emailHasError = false;
  for (value of controlValue) {
    const ctrl = new FormControl(value, validator);
    if (Object.keys(validator(ctrl)).length) {
      emailHasError = true; // if any of the values are invalid
    }
  }
  return emailHasError; // or return whatever you need to.
}

也许像这样使用它

validate(validators: ValidatorFn[], c: FormControl) {
  const allErrors: any = {};
  for (const validator of validators) {
    if (Array.isArray(c.value)) {
      if (this.isControlValid(c.value, validator)) {
        // maybe update `allErrors` here or something

你可以随心所欲地实现它,但这个想法只是使用它自己的表单控件来验证每个字符串。

可能有一些晦涩的方法可以使用不同的方式实现这一目标,NG_VALIDATORS但我没有研究过。

于 2020-10-16T18:43:22.487 回答
1

我如何从我的自定义验证函数中知道哪个验证器是从父级设置的?是 Validators.required,Validators.email

每个验证器函数都返回一个错误对象。如果您看到 Validators.email() angular,它会返回{ 'email': true }对象。因此,如果您遍历control.errors(或hasError在您的示例中),您可以检查任何对象的键是否匹配email-

static email(control) {
        if (isEmptyInputValue(control.value)) {
            return null; // don't validate empty values to allow optional controls
        }
        return EMAIL_REGEXP.test(control.value) ? null : { 'email': true };
    }

以下是您的validate()功能的外观 -

validate(validators: ValidatorFn[], c: FormControl) {
    const allErrors: any = {};
    for (const validator of validators) {
      const hasError = validator(c);
      if (hasError) {
        Object.entries(hasError).forEach(([errorName, isOnError]) => {
          if(errorName === 'email' ) {
            console.log('Validators.email was set');
          }
          allErrors[errorName] = isOnError;
        });
      }
    }

    if (Object.keys(allErrors).length > 0) {
      return allErrors;
    }

    return null;
  }
于 2020-10-14T13:26:07.817 回答