Angular 2中的条件验证 [英] Conditional validation in Angular 2

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

问题描述

Angular 2中的验证非常简单,非常棒.但是,如果选择了其他字段,如何将必填字段设为可选.

Validation in Angular 2 is pretty straight forward which is awesome. However, how would one go about making a required field optional if some other field is selected.

这是我的规则

this.contractsFilter = this.fb.group({
  selectedContractType: ['', [Validators.required]],
  selectedYear: ['', [Validators.required]],
  selectedPde: ['', [Validators.required]],
  refNo: ['', []]
});

如果用户提供了refNo,我希望标记为必填项的其他字段为不需要".

I want other fields flagged as required to be 'un-required' if the refNo is provided by the user.

推荐答案

使用自定义验证器和setValidators都可以很快变得非常复杂.我更喜欢根据需要配置验证器,然后有条件地启用或禁用它们.

Both the use of custom validators and setValidators can get very complex very quickly. I prefer to configure the validators as they may be required and then conditionally enable or disable them.

完全使用您的代码:

this.contractsFilter = this.fb.group({
  selectedContractType: ['', [Validators.required]],
  selectedYear: ['', [Validators.required]],
  selectedPde: ['', [Validators.required]],
  refNo: ['', []]
});

然后我将为refNo订阅valueChanges:

this.contractsFilter.controls['refNo'].valueChanges.subscribe(value => {
  if (value) { // There is a refNo specified
    this.contractsFilter.controls['selectedContractType'].disable();
    this.contractsFilter.controls['selectedYear'].disable();
    this.contractsFilter.controls['selectedPde'].disable();
  } else {
    this.contractsFilter.controls['selectedContractType'].enable();
    this.contractsFilter.controls['selectedYear'].enable();
    this.contractsFilter.controls['selectedPde'].enable();
  }
});

现在,所有验证器都在一个一致的位置中指定,您仍然可以控制是否执行验证器.

Now your validators are all specified in one consistent place, and you can still control whether the validators are executed or not.

这篇关于Angular 2中的条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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