Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 914
Flo Avatar asked Oct 22 '25 01:10

Flo


2 Answers

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

like image 103
hevans900 Avatar answered Oct 24 '25 14:10

hevans900


Why not disable the controls that aren't needed - then they don't get validated?

like image 37
Simon_Weaver Avatar answered Oct 24 '25 15:10

Simon_Weaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!