8

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;
}
3
  • 1
    Not sure the CSS has to do with that, but try this.formGroup.updateValueAndValidity(). Commented Oct 18, 2018 at 13:45
  • 1
    I tested, and it doesn't trigger my css status classes Commented Oct 18, 2018 at 13:56
  • As said, I don't think your CSS issue has to do with the form validation. I think that the detection provided isn't what suits you best. Let me give you a suited answer. Commented Oct 18, 2018 at 14:01

3 Answers 3

12

You can programmatically trigger the validator using the following.

this.formGroup.controls['controlNameHere'].markAsTouched();
Sign up to request clarification or add additional context in comments.

Comments

3

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'
})

1 Comment

this is a nice simple approach to adding maxLength validation to a specific formControl input and per the stackblitz you shared an easy way to throw the validation error in the HTML <div class="error" *ngIf="first.hasError('maxlength')">Task can be max 40 characters long.</div>
3

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);
    }
  });
}

Comments

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.