2016-11-24 42 views
0

我想在提交時也顯示消息,所以請糾正我如何驗證提交。 這裏我的HTML表單組驗證

<input type="text" class="form-control" formControlName="code" required> 
<label [hidden]="ascForm.controls.code.valid || (ascForm.controls.code.pristine && ascForm.submitted)" class="errorMsg">Cannot save. You must specify a code.</label> 

此驗證條件是工作的罰款,如果我使用模板驅動的方法, 但現在我使用的模型驅動的,所以請大家指正提交條件。

回答

1

常見的方法是禁用提交按鈕,直到形式是完全有效的。

但是,如果您只想在用戶實際提交表單時顯示消息,請在您的FormComponent布爾屬性中創建,指示用戶嘗試發佈表單。像:

submitAttempt: boolean = false; 

並提交表單,在你的組件將其設置爲true

submitForm() { 
    this.submitAttempt = true; 
    ... 
    } 

然後,您可以過濾你的信息只是submitAttempt == true。像:

<span *ngIf="!code.valid && submitAttempt">Required</span> 

對於深解釋,看到這個帖子:Angular 2 forms validation搜索頁面 'submitAttempt' 快速找到所引用的部分

PS:請不要使用label標籤顯示驗證錯誤。它應該僅用於標記表單輸入。

+0

感謝您的建議,它是這種情況的良好替代品。 – coder