angular 5 conditionally validate field based on another field's value

巧了我就是萌 提交于 2020-07-09 13:27:45

问题


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 ]
    [...]
})

回答1:


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.

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



来源:https://stackoverflow.com/questions/52911267/angular-5-conditionally-validate-field-based-on-another-fields-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!