【问题标题】:angular 5 conditionally validate field based on another field's valueangular 5 根据另一个字段的值有条件地验证字段
【发布时间】:2019-03-25 11:04:30
【问题描述】:

如何根据另一个字段的值有条件地验证一个字段?这是我尝试过的方法,但似乎不起作用

this.PDform = _formbuilder.group({
    [...]
    'intlNumber': ['',this.nationality == 'Abroad' ? Validators.compose([Validators.pattern(this.phoneNumberExp), Validators.maxLength(14), Validators.minLength(11), Validators.required]) : Validators ]
    [...]
})

【问题讨论】:

标签: angular angular5 angular-reactive-forms angular-forms angular-validation


【解决方案1】:

当另一个表单控件的值发生变化时,您可以通过订阅表单控件实例提供的valueChanges observable 来更改表单控件的验证器:

const control1 = <FormControl>this.form.get('control1');
const control2 = <FormControl>this.form.get('control2');

control1.valueChanges.subscribe(value => {
  if (value === 'first-condition') {
    control2.setValidators([Validators.required, ...])
  }
  else {
    control2.setValidators(null);
  }

  control2.updateValueAndValidity();
});

这是一个人为的示例,但该模式可以根据您的用例进行调整。不要忘记将订阅分配给您的视图模型,并在您的控件被销毁时取消订阅。

这是一个 StackBlitz 示例:https://stackblitz.com/edit/conditional-validation

【讨论】:

  • 感谢您的回复。但是,它似乎不起作用。我在控制台Cannot read property 'valueChanges' of null 中收到此错误。请问我该如何解决
  • 你什么时候实例化你的表单?
  • ngOnInit()上实例化
  • 你可以在初始化表单后直接放这段代码。
  • 尝试在ngAfterViewInit() 中设置它并返回相同
猜你喜欢
  • 1970-01-01
  • 2021-01-19
  • 2018-09-04
  • 2011-09-20
  • 2017-02-28
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多