如何使用嵌套表单组验证活动表单?

时间:2017-03-22 02:42:09

标签: angular typescript angular2-forms reactive-forms

我正致力于创建嵌套表单组,如https://plnkr.co/edit/c93yFe2r83cvjiRvl6Uj?p=preview所示。

这是来自https://angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive

的示例分支

Angular中的示例显示当表单没有任何嵌套组时使用validationMessages。我有嵌套表单组时,我不确定如何扩展它。以下是我要创建的示例表单和验证消息。

  buildForm(): void {
    this.heroForm = this.fb.group({
      'name': [this.hero.name, [
          Validators.required,
          Validators.minLength(4),
          Validators.maxLength(24),
          forbiddenNameValidator(/bob/i)
        ]
      ],
      'address': this.fb.group({
        'city': [''],
        'state': ['']
      }),
      'alterEgo': [this.hero.alterEgo],
      'power':    [this.hero.power, Validators.required]
    });

    this.heroForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

预计formErrorsvalidationMessages

  formErrors = {
    'name': '',
    'power': '',
    'address': {
      'state': '',
      'city': ''
    }
  };

  validationMessages = {
    'name': {
      'required':      'Name is required.',
      'minlength':     'Name must be at least 4 characters long.',
      'maxlength':     'Name cannot be more than 24 characters long.',
      'forbiddenName': 'Someone named "Bob" cannot be a hero.'
    },
    'power': {
      'required': 'Power is required.'
    },
    'address': {
      'city': {
        'required':      'City is required.',
        'minlength':     'City must be at least 4 characters long.',
      },
      'state': {
        'required':      'State is required.',
        'minlength':     'State must be at least 4 characters long.',
      }
    }
  };

以下是onValueChanged

  onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

如何更新上述onValueChanged函数以支持嵌套表单组验证?

我上面做的是因为我有一个向导表单,我想在移动到向导的下一步之前验证嵌套表单组。每个向导步骤都包含一个嵌套的表单组。在转到下一步之前,当前向导步骤必须有效。我不想将向导的内容放入多个组件中,因为必须将来自向导的所有数据一起提交到远程服务。因此,我不会因为有多个组件而看到复杂的价值。

0 个答案:

没有答案