2017-09-27 110 views
0

我做驗證的角度如下:對角形式提交驗證

<form #f="ngForm" (ngSubmit)="save(f.value, f.valid)" novalidate > 

    <input type="email" name="txtEmail" id="txtEmail" required 
      [(ngModel)]="model.txtEmail" #txtEmail="ngModel"> 
     <div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">E-Mail invalid</div> 

    <button type="submit">Submit</button> 

</form> 

我怎樣才能觸發形式驗證提交?只有在輸入中按下鍵時才起作用。

+0

我將現在只更新了我的答案。我認爲這是提交後驗證字段的最佳方法。希望這對你有用。 – Chandru

回答

0

我發現了一個解決方案。我改變:

<div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">bitte die E-Mail Adresse angeben! </div> 

<div [hidden]="txtEmail.valid || (txtEmail.pristine && !f.submitted)" class="text-danger">bitte die E-Mail Adresse angeben! </div> 
0

我認爲這是提交後驗證字段的方式。的例子如下:

component.html

<form name="editForm" role="form" novalidate (ngSubmit)="save(editForm)" #editForm="ngForm" class="form-horizontal"> 
    <input type="text" class="form-control" [(ngModel)]="model.txtEmail" name="txtEmail" id="txtEmail" required> 
    <div [hidden]="!(editForm.controls.txtEmail?.dirty && editForm.controls.txtEmail?.invalid)"> 
     <small class="form-text text-danger" 
      [hidden]="!editForm.controls.txtEmail?.errors?.required"> 
      This field is required. 
     </small> 
    </div> 
    <button type="submit" type="submit">Save</button> 
</form> 

component.ts

import { NgForm } from '@angular/forms'; 

export class AppComponent { 
    private model: any = {}; 
    private editForm: NgForm; 

    save(form: NgForm) { 
     this.editForm = form; 
     Object.keys(this.editForm.controls).forEach(key => { 
      this.editForm.controls[key].markAsDirty(); 
     }) 
    } 
} 
+0

我不想禁用提交按鈕。必須有辦法在提交 – daniel

+0

更新我的答案時運行驗證。我認爲這是提交後驗證字段的最佳方法。希望這會有用 – Chandru