单击按钮上的angular2验证表单 [英] angular2 validate form on button click

查看:81
本文介绍了单击按钮上的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
}

前提是您在

<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验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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