角度反应形式的条件要求验证 [英] Conditional required validation in angular reactive form

查看:30
本文介绍了角度反应形式的条件要求验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据其他一些表单值对某些属性应用条件验证.我已经提到了一些答案 Angular2: Conditional required validation,但这些都不能满足我的需要.因为我必须在我的大型企业应用程序的 40 多种形式(大约 30 个字段)中实现条件验证.我不想在每个组件中编写相同的代码并更改 FormControl 名称.我不知道如何通过指令实现这一点.

I want to apply conditional validation on some properties based on some other form values. I have referred some answers Angular2: Conditional required validation, but those are not fulfil my need. Because I have to implement conditional validation in 40+ form(around 30 fields) of my large enterprise application. I don't want write the same code in every component and change the FormControl name. I don't know how this can be achieved via Directive.

如果年龄控制值 v 大于 18,则许可证号字段是必需的.

if age control valuev is greater than 18 than the license number field is required.

这是我的代码:

this.userCustomForm = this.angularFormBuilder.group({
age:['',Validators.required],
licenseNo:[''] // Here I want to apply conditional required validation.
});

在我的应用程序中,有些情况下我想根据嵌套的 FormGroupFormArray 值设置条件验证.

In my application there are some cases where I want set conditional validation based on nested FormGroup or FormArray values.

请指导我,我怎样才能做到这一点.

Please guide me, how can I achieve this.

推荐答案

对我来说它完美是这样的:

this.userCustomForm.get('age').valueChanges.subscribe(val => {
  if (condition) {
    this.userCustomForm.controls['licenseNo'].setValidators([Validators.required]);
  } else {
    this.userCustomForm.controls['licenseNo'].clearValidators();
  }
  this.userCustomForm.controls['licenseNo'].updateValueAndValidity();
});

您必须updateValueAndValidity 使更改生效.

希望这会有所帮助!

这篇关于角度反应形式的条件要求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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