本文介绍了angular2 在按钮单击时验证表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 button type="submit" 提交表单,表单验证消息就会出现,一切都很好.但是,如果我有一个带有 (click)="myhandler()" 的按钮(或链接),则不会出现验证.

If I submit a form using button type="submit" the form validation messages appear and everything is fine. However if I have a button (or link) with (click)="myhandler()" then the validations do not appear.

我该怎么做:

  • 将元素标记为需要验证器运行,或
  • 以编程方式运行并显示验证消息.

注意:这些是简单的验证,例如输入字段上的必需项.

Note: These are simple validations like required on input fields.

示例代码:

<form (ngSubmit)="save()">
  <input required type='text' [(ngModel)]="name">
  <!-- Shows validation messages but still calls save() -->
  <button (click)="save()">Click</button>
  <!-- Only submits if valid and shows messages -->
  <button type="submit">Submit</button>
</form>
<!-- does not even show validation messages, just calls save -->
<button (click)="save()">Click 2</button>

推荐答案

请注意:此方法适用于响应式表单.

Please note: this approach is for reactive forms.

我使用 markAsTouched() 属性在按钮点击时运行验证.

I used markAsTouched() property to run validations on a button click.

假设以下按钮在表单之外:

Suppose the following button is outside the form:

<button type="button" (click)="validateForm()">Submit</button>

现在,在 validateForm 方法中,如果表单无效,您可以为每个表单控件设置 markAsTouched() 属性,angular 将显示验证消息.

Now, in the validateForm method if the form is invalid, you can set markAsTouched() property for each of the form controls and angular will show validation messages.

validateForm() {
    if (this.myformGroup.invalid) {
      this.myformGroup.get('firstName').markAsTouched();
      this.myformGroup.get('surname').markAsTouched();
      return;
    }
    // do something else
}

前提是您在 html 中设置了验证消息,例如

provided you have validation messages setup in your html like

<mat-error *ngIf="myformGroup.get('firstName').hasError('required')">
  first name is required
</mat-error>

并且您在表单组构建器中设置了必需的字段验证,例如

and you have required field validation setup in your form group builder like

firstName: ['', Validators.required]

这篇关于angular2 在按钮单击时验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 23:07