Search code examples
angularformstypescriptangular7angular-forms

Angular 7 Forms - Conditionally require FormGroup


I am building a form where the user can set payment options. There is a dropdown to choose which payment method will be used. For every payment mehod there is a FormGroup with options for the selected method:

form: FormGroup = new FormGroup({
        method: new FormControl('paypal', {
            validators: [
                Validators.required,
            ],
        }),
        paypal: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
        other: new FormGroup({
            email: new FormControl(null, {
                validators: [
                    Validators.required,
                    Validators.pattern(EMAIL_PATTERN)
                ],
            }),
        }),
    });

The issue here is, that the form will only be valid if both FormGroups are valid.

But the form should be valid as soon as the FormGroup for the selected payment method is valid.


Solution

  • I would suggest writing a custom root-level FromGroup validator. You essentially have a bespoke validation requirement, and it needs a bespoke validator.

    Validators can work on entire FormGroups as well as individual FormControls, because they are both AbstractControls under the hood.

    This should point you in the right direction

    Edit: for anyone looking for a quick answer here's a stackblitz: nested form validation