【问题标题】:Angular Dynamic Form Example With Multiple Validators具有多个验证器的 Angular 动态表单示例
【发布时间】:2017-12-27 22:39:22
【问题描述】:

Angular 官方文档有一个 dynamic form tutorial 包含动态表单的故事。服务用于创建 FormGroup 对象,如下所示:

    toFormGroup(questions: QuestionBase<any>[] ) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                              : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }

如何向每个 FormControl 对象添加多个验证器函数?以下似乎不起作用:

questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', [Validators.required, Validators.maxLength(12)])
                                              : new FormControl(question.value || '');
    });

我也试过Validators.compose([Validators.required, Validators.maxLength(12)]),它也没有按预期工作。似乎应用的唯一验证器是“必需”验证器。这是一个 plnkr 演示该行为。上述代码包含在 question-control.service.ts 文件中。

我试图实现的预期结果是将 maxLength 验证器也应用于 FirstName 控件。

【问题讨论】:

  • @Vega 代码直接来自 angular.io 网站。所做的唯一修改是将验证器数组添加到 FormControl 构造函数的第二个参数
  • 验证器在您的 plunkr 中工作...您期望的结果是什么?

标签: javascript angular validation


【解决方案1】:

您可以做的是将每个问题的必要验证放在一个数组中,我是这样做的:

toFormGroup(questions: QuestionBase<any>[] ) {
    const group: any = {};
    let validaciones = [];
    questions.forEach(question => {
      if (question.required) {
        validaciones.push(Validators.required);
      }
      // Validación para solo números
      if (question.number) {
        validaciones.push(Validators.pattern(/^([0-9])*$/));
      }

      group[question.key] = new FormControl(question.value || '', validaciones);
      validaciones = [];

    });

如果您想看一下,我将我的存储库留在 GitHub 上 https://github.com/aleRozo/formulariosDinamicos/

【讨论】:

    【解决方案2】:

    验证实际上已经到位,但目前您只需对字段是否无效进行通用检查:

    <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
    

    如果该字段无效,那当然会显示此消息。

    快速的解决方法是检查哪个错误字段有:

    <div class="errorMessage" *ngIf="form.controls[question.key].hasError('required')">
       {{question.label}} is required
    </div>
    <div class="errorMessage" *ngIf="form.controls[question.key].hasError('maxlength')">
       {{question.label}} is too long
    </div>
    

    plunker:https://plnkr.co/edit/RQRQiJfQbnOHEPuS0jji?p=preview

    但是由于您的表单是动态的,我猜您还想要一个尽可能动态的验证。为此,我建议您查看 official docs 中的此示例,这些示例使用对象 formErrors 和 validationMessages 并存储了所有验证消息,然后在任何时候将它们与此方法一起使用表格有变化:

    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] + ' ';
          }
        }
      }
    }
    

    【讨论】:

    • 验证似乎没有到位,因为表单在第一个字符输入时有效
    • 我不知道...如果名称太长,至少显示表单无效:plnkr.co/edit/n5Y6Z0UCwjSd3ZfRfvvK?p=preview
    • 你有 maxlength 而不是 minlength 的验证器,这有什么令人困惑的地方吗?
    • 长时间盯着屏幕的后果。你的权利。感谢您的帮助。
    • 发生在我们所有人身上 ;) 很高兴我能帮上忙,迈克周末愉快,编码愉快,但记得在这期间让你的眼睛和大脑休息一会儿:P
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2019-06-12
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    相关资源
    最近更新 更多