Joba
Joba

Reputation: 898

How can I validate reactive form controls programmatically?

I have a FormGroup object of my reactive form. Now I want to trigger the form validation programmatically.

I already check the form with this code, but my control css status classes aren't set, like it's done when I click the control and click outside the control.

if (!this.formGroup.valid) {
  // TODO: Fix that invalid controls don't get highlighted
  return;
}

Upvotes: 7

Views: 8564

Answers (3)

WasiF
WasiF

Reputation: 28939

Validate all form fields

validateAllFormFields(formGroup: FormGroup) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);

    if (control instanceof FormControl) {
      control.markAsTouched({ onlySelf: true });
    } 
    else if (control instanceof FormGroup) {
      this.validateAllFormFields(control);
    }
  });
}

Upvotes: 3

Marshal
Marshal

Reputation: 11101

You can programmatically trigger the validator using the following.

this.formGroup.controls['controlNameHere'].markAsTouched();

Upvotes: 12

user4676340
user4676340

Reputation:

When you create a reactive form, you implicitly says that the form should update its values and validity on a specific strategy.

There are 3 strategies :

  • On blur
  • On change
  • On submit

You can change the update strategy when you create your form controls or your form group. In your case, the change strategy should work.

Here is a stackblitz containing both strategies, see what suits you best.

first = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'blur'
})
second = new FormControl('', {
  validators: [Validators.minLength(3)],
  updateOn: 'change'
})

Upvotes: 3

Related Questions