2016-11-24 41 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