0
votes

I have a form that uses FormGroup.

I want to add validator to some controls that contain data (after user has entered data and clicked on 'check' button.)

I tried this:

this.fg.controls['someKey'].setValidators([Validators.required]);

and

this.fg.controls['someKey'].updateValueAndValidity();

but it clears the data from the control.

Any idea?

1
Hmm... could you create a plunker, based on this little information I could not reproduce the issue...AJT82
Click Me for custom validations stackoverflow.com/a/38092249/5868331mayur

1 Answers

0
votes

you can set a validators like that. try this

formBuilder

 this.fg = this.formBuilder.group(
     exampleGroup: this.formBuilder.group({
                        checkboxInput: [false],
                        textinput: [''],
                    }, {validator: this.requiredIfChecked}),   
    }

custom validators function

  requiredIfChecked(control: AbstractControl): void {
            const input = control.get('textInput').value;
            const inputCheckbox = control.get('checkboxInput').value;
            control.get('textinput').setValidators([]);
            if (inputCheckbox) {
                if (input === '' || input === null) {
                  control.get('textInput').setValidators([Validators.required]);
                }
            }
        }

also you can do that second way see DEMO