Angular 2反应形式在提交时触发验证 [英] Angular 2 Reactive Forms trigger validation on submit

查看:93
本文介绍了Angular 2反应形式在提交时触发验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在提交时触发所有反应形式的验证器,而不仅是脏"和触摸"事件?

is there a way that all validators of a reactive forms can be triggered upon submit and not only by the "dirty" and "touch" events?

这样做的原因是我们有一个很大的表格,它不能指示是否需要一个字段,并且用户可能会错过一些必需的控件,因此在提交时,可以预期所有无效字段将显示最终用户错过的内容.

The reason for this is we have a very large forms which doesn't indicate if a field is required or not, and user might miss some of the required control, so upon submit, it is expected that all of the invalid fields which are missed by the end user will be shown.

我尝试使用

FormGroup.markAsTouched(true);

它起作用了,所以我也尝试将其标记为脏"

it worked, and so I also tried marking it as "dirty"

FormGroup.markAsDirty(true);

但是该类的css仍然是"ng-pristine",

but the css of the class is still "ng-pristine",

有没有一种方法可以从组件中手动触发它,我尝试用谷歌搜索它无济于事,谢谢您!

Is there a way to trigger it manually from the component, I tried googling it to no avail, thanks you in advance!

更新

我已经通过迭代FormGroup.controls并将其标记为"dirty"使其工作,但是有标准"方式可以做到这一点.

I already got it working by iterating the FormGroup.controls and marking it as "dirty", but is there a "standard" way to do this.

推荐答案

这可以通过提供的示例实现

This can be achieved with the sample presented here, where you can make use of NgForm directive:

<form [formGroup]="heroForm" #formDir="ngForm">

,然后在您的验证消息中检查表单是否已提交:

and then in your validation messages just check if the form is submitted:

<small *ngIf="heroForm.hasError('required', 'formCtrlName') && formDir.submitted">
  Required!
</small>

现在还提供了{ updateOn: 'submit'},但是仅当您在表单上没有required时,该方法才有效,因为无论如何最初都会显示required.您可以通过检查字段是否被触摸来抑制这种情况.

Now is also { updateOn: 'submit'} is provided, but that works only if you do not have required on the form, as required is displayed initially anyway. You can suppress that with checking if field has been touched though.

// fb is 'FormBuilder'
this.heroForm = this.fb.group({
 // ...
}, { updateOn: 'submit'})

这篇关于Angular 2反应形式在提交时触发验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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