1

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.

1
  • Can you share your code? Commented Mar 29, 2019 at 12:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.