Gausmohammad Shaikh
Gausmohammad Shaikh

Reputation: 59

How to apply validation in angular 7 reactive forms on submit?

TS Code:

onSubmit(){
 if(this.Registration.invalid){
   return;
  }
alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

}

HTML Code:

<form class="admin-form" [formGroup]="Registration" (ngSubmit)="onSubmit()" id="Registration">
    <mat-form-field appearance="outline">
        <mat-label>username</mat-label>
        <input matInput class="matInput" placeholder="username" type="text" formControlName="username">
    <mat-icon matSuffix>person</mat-icon>
      <mat-error *ngIf="Registration.controls['username'].invalid && (Registration.controls['username'].dirty ||Registration.controls['username'].touched)">
        <div *ngIf="Registration.controls['username'].errors.required">
          username is required.
        </div>
        <div *ngIf="Registration.controls['username'].errors.pattern">
          username must be characters and special characters.
        </div>
       </mat-error>
  </mat-form-field>
  <button mat-icon-button type="submit" value="submit">
    <i class="material-icons">send</i>
  </button>
</form>

Angular 7 reactive forms validation on the submit button, I want if there any errors or input field empty, then the form should be not submitted successfully.

Upvotes: 1

Views: 733

Answers (1)

Prashant Pimpale
Prashant Pimpale

Reputation: 10717

Remove ! because it returns true when the form in Invalid i.e it has errors and returns false when then the form is Valid like:

if (this.Registration.invalid) {
   return;
}

alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

But it's better to use form.valid to check the form Validation, explain here

So the change with valid is use !:

if (!this.Registration.valid) {
   return;
}

alert('Thanks for submitting! Data:' + JSON.stringify(this.Registration.value));

Another way and Recommended:

You can also disable the button itself if the form is invalid so until the form gets valid the submit button will be disabled for ex:

[disabled]="!Registration.valid" OR [disabled]="Registration.invalid"

with button:

<button mat-icon-button type="submit" [disabled]="!Registration.valid" value="submit">
  <i class="material-icons">send</i>
</button>

Stackblitz_Example

Upvotes: 1

Related Questions