How to Check if a Reactive Form is Valid or not in Angular?

To check if a form is valid or not, you can use the form.valid property. The valid property returns true if the form is valid. Otherwise, it returns false.

This is how you can check it in your ts file:

submitForm(){
    if(this.form.valid){
      // Form is valid
      // Add other stuff here
    }else{
      // Form is not valid
    }
}

Example:

Let’s understand the form validation with a real-world example.

Let’s say we have a form which contains the firstName, lastName and the age of a student:

<form [formGroup]="form">
    First Name: <input type="text" formControlName="firstName"><br><br>
    Last Name: <input type="text" formControlName="lastName"><br><br>
    Age: <input type="text" formControlName="age" maxlength="2"><br><br>
    <button (click)="submitForm()" >Submit</button>   <!-- Submit the form -->
</form>

Now, let’s create the form in our ts file using the FormBuilder. The form builder lets you easily group the form controls using the FormBuilder.group() method.

In our template file, we have bound a click event handler function submitForm() with the submit button. This function gets invoked whenever the user clicks on the submit button.

Next, we need to check if the form is valid or not inside the submitForm() function. Which we can very easily do using the form.valid property.

Here is the ts file with full code:

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class CompOneComponent implements OnInit {

  form: FormGroup;

  constructor(private fb: FormBuilder) {
    // Create the form
    this.form = this.fb.group({
      'firstName': ['', Validators.required],
      'lastName': ['', Validators.required],
      'age': ['', Validators.required]
    })
  }

  ngOnInit(): void {
  }

  submitForm() {
    if (this.form.valid) {
      // Form is valid
      // Add other stuff here
    } else {
      // Form is not valid
    }
  }
}

If you want to keep the submit button disabled until the user fills in all the mandatory details, you can bind the disabled property of the button with the form.valid property.

This is how you can do it inside the template file:

<button (click)="submitForm()" [disabled]="!form.valid">Submit</button>

This will keep the button disabled(not clickable) until all the form fields are filled. As soon as you fill in all mandatory form fields, the button will become enabled automatically.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.