具有多个验证器的角度动态表单示例 [英] Angular Dynamic Form Example With Multiple Validators

查看:103
本文介绍了具有多个验证器的角度动态表单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方Angular文档包含动态表单教程,其中包含动态表单的故事。服务用于创建FormGroup对象,如下所示:

The official Angular docs have a dynamic form tutorial containing a story for dynamic forms. A service is used to create the FormGroup object like so:

    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对象添加多个验证器函数?以下似乎不起作用:

How can I add more than one validator function to each FormControl object? The following doesn't seem to work:

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文件中。

I've also tried Validators.compose([Validators.required, Validators.maxLength(12)]) which doesn't work as expected either. The only validator that seems to be applied is the 'required' validator. Here is a plnkr demonstrating the behavior. The code mentioned above is contained in the question-control.service.ts file.

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

The expected outcome i'm trying to achieve is to have the maxLength validator also applied to the FirstName control.

推荐答案

验证实际上已到位,但目前您只需进行一般检查,如果该字段无效与否:

The validations are actually in place, but currently you just have a generic check if the field is not valid or not:

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

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

That will of course display this message if the field is not valid.

快速解决方案是检查哪个错误字段:

The quick solution is to check which error field has:

<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

但由于您的表单是动态的,我想你也想要一个尽可能动态的验证。为此,我建议您从 官方文档 正在使用对象 formErrors validationMessages 存储验证消息,然后在表单发生变化时将这些消息与此方法一起使用:

But since your form is dynamic, I guess you also want a validation that is as dynamic as possible. For that I suggest you take a look at this sample from the official docs which are using an object formErrors and validationMessages with all validation messages stored, and then using these together with this method whenever there are changes in the form:

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

这篇关于具有多个验证器的角度动态表单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆