繁体   English   中英

如果表单项为空,但用户提交表单,则在Angular2表单中显示错误

[英]Show errors in Angular2 forms if form items empty, but user submit form

我有一个userForm组,其中包含键nameemailphone 我还有一个onValueChanged函数,该函数可以订阅以进行表单更改并验证数据。

 buildForm(): void {
    this.userForm = this.fb.group({
      'name': ['', [
          Validators.required,
        ]
      ],
      'email': [''],
      'phone':    ['', Validators.required]
    });

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

我也有一个提交按钮,但是如果用户不打印任何数据并提交表单,我的错误就不会显示。 我该如何解决?

onSubmit() {
    this.submitted = true;
}

这是我的错误:

formErrors = {
    'name': '',
    // ...
  };

  validationMessages = {
    'name': {
      'required':      'Name is required.',
      'minlength':     'Name must be at least 4 characters long.',
      // ...
    },
    // ...
  };
}

我的onValueChanged函数:

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

    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control: any = form.controls[field];

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

我在这样的模板中使用验证:

<div [ngClass]="formErrors.email ? 'has-danger' : '' ">
    <label for="email">Email <span class="text-danger">*</span></label>
    <input type="email" formControlName="email"  id="email">
    <div class="form-control-feedback">{{formErrors.email}}</div>
</div>

您需要在component.html(html或html文件)中编写ngif语句。 如下面针对phone formControl:

  <div *ngIf="!phone.valid && (phone.touched || submitted)">Required</div>

添加了phone.touched ,以便仅在用户触摸formControl之后才会显示错误。

添加了submitted ,因此仅在用户尝试提交表单后才会显示错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM