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

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

问题描述

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

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 并将其标记为脏"来让它工作,但是有没有一种标准"的方法来做到这一点.

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

推荐答案

这可以通过提供的示例来实现 此处,您可以在此处使用 NgForm 指令:

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 Reactive Forms 在提交时触发验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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