angular 5 基于另一个字段的值有条件地验证字段 [英] angular 5 conditionally validate field based on another field's value
问题描述
如何根据另一个字段的值有条件地验证一个字段?这是我尝试过的,但似乎不起作用
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 ]
[...]
})
推荐答案
当另一个表单控件的值发生变化时,您可以通过订阅由表单控件实例:
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
这篇关于angular 5 基于另一个字段的值有条件地验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!