10

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 ]
    [...]
})
4
  • Is this.nationality supposed to be another form control? or? Commented Oct 21, 2018 at 0:54
  • Possible duplicate of Conditional validation in Angular 2 Commented Oct 21, 2018 at 1:37
  • 1
    For multiple property validation, it may be better to use one validator, that triggers whenever any input will change in that group of properties. There is a way to do this by grouping those properties in a sub form. Commented Oct 21, 2018 at 1:58
  • Does this answer your question? Angular 4 form validation on multiple fields Commented Feb 23, 2020 at 10:23

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for your response. However, it seems not to be working. I got this error in the console Cannot read property 'valueChanges' of null. How do i fix it please
When are you instantiating your form?
Instantiated on ngOnInit()
You can put this code directly after you initialize your form.
Tried setting it in ngAfterViewInit() and it returns same
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.