角度5根据另一个字段的值有条件地验证字段 [英] angular 5 conditionally validate field based on another field's value

查看:117
本文介绍了角度5根据另一个字段的值有条件地验证字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to conditionally validate a field based on another field's value? Here's what i've tried but it seems not to work

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

推荐答案

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

You can change the validators for a form control when the value of another form control changes by subscribing to the valueChanges observable provided by the form control instance:

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();
});

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

This is a contrived example, but the pattern can be adapted for your use case. Don't forget to assign the subscription to your view model and unsubscribe when your control is destroyed.

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

Here's a StackBlitz example: https://stackblitz.com/edit/conditional-validation

这篇关于角度5根据另一个字段的值有条件地验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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