Search code examples
angulartypescriptangular2-form-validation

How to prevent form submit until all validations are passed [Angular 7]


I am new to Angular. I have read this, this and this question thoroughly, But none of them are of my use as they are using jquery. My form is pretty basic registration form with only 4 basic fields. Username, password, confirm password and zipcode and a submit button. To keep this post clean and there are multiple files involved I've uploaded necessary files on github.

  1. app.component.html
  2. app.component.ts
  3. app.module.ts

And I am handling validators for password and zipcode separately in

  1. validator.ts

Validations are working perfectly fine. But the problem is that the form still gets submitted even when there are validation issues on frontend. Here is my screenshot. Please suggest me a solution or at least give some hint.

PS: I am following this youtube tutorial.

enter image description here


Solution

  • First, disable the button

    <button type="submit" class="btn btn-primary" (click)="onSubmit()" [disabled]="!form.valid">Submit</button>
    

    Next, use a condition before submit.

      onSubmit(){
        if (!this.form.valid) return;
    
        // console.log(this.form.controls.zip);
        this.form.markAsTouched();
        console.log(this.form.value);
    
      }
    

    Finally, add that attribute to your form :

    <form [formGroup]="form" novalidate>