如何在提交时应用角度7反应形式的验证?

问题描述 投票:1回答:1

TS代码:

onSubmit(){
 if(this.Registration.invalid){
   return;
  }
alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

}

HTML代码:

<form class="admin-form" [formGroup]="Registration" (ngSubmit)="onSubmit()" id="Registration">
    <mat-form-field appearance="outline">
        <mat-label>username</mat-label>
        <input matInput class="matInput" placeholder="username" type="text" formControlName="username">
    <mat-icon matSuffix>person</mat-icon>
      <mat-error *ngIf="Registration.controls['username'].invalid && (Registration.controls['username'].dirty ||Registration.controls['username'].touched)">
        <div *ngIf="Registration.controls['username'].errors.required">
          username is required.
        </div>
        <div *ngIf="Registration.controls['username'].errors.pattern">
          username must be characters and special characters.
        </div>
       </mat-error>
  </mat-form-field>
  <button mat-icon-button type="submit" value="submit">
    <i class="material-icons">send</i>
  </button>
</form>

对于提交按钮的Angular 7被动表单验证,我想如果有任何错误或输入字段为空,那么表单应该不能成功提交。

html5 typescript angular7
1个回答
1
投票

删除!,因为它返回true时,表单为Invalid,即它有错误,并返回false,然后表单有效,如:

if (this.Registration.invalid) {
   return;
}

alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

但最好使用form.valid检查表格验证,解释here

因此valid的变化是使用!

if (!this.Registration.valid) {
   return;
}

alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

另一种方式和推荐:

如果表单无效,您也可以禁用按钮本身,因此在表单生效之前,提交按钮将为disabled for ex:

[disabled]="!Registration.valid" OR [disabled]="Registration.invalid"

带按钮:

<button mat-icon-button type="submit" [disabled]="!Registration.valid" value="submit">
  <i class="material-icons">send</i>
</button>

Stackblitz_Example

© www.soinside.com 2019 - 2024. All rights reserved.