email validation in angular 6?

Viewed 6349

I have a form in angular6 with an email form field.

The email form field has email validation which properly shows the error message when email is invalid. But the form is still saved if I click the "Save" button. How can I show the error message, but not save the user when clicked?

Important requirement is that I don't want to disable the "Save" button.

user.component.html

<form method="post" enctype="multipart/form-data">
  <mat-form-field>
   <input matInput placeholder="Enter your Username" [(ngModel)]="userObj.userName" name="username" required>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Enter your email" [formControl]="email" [(ngModel)]="userObj.emailid" name="emailid" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>                   
</form>

<button mat-raised-button color="primary" (click)="saveNewUserDetails()">Save User</button>

user.component.ts

import {FormControl, Validators} from '@angular/forms';
email = new FormControl('', [Validators.required, Validators.email]);

getErrorMessage() {
  return this.email.hasError('required') ? 'You must enter a value' :
    this.email.hasError('email') ? 'Not a valid email' : '';
}

saveNewUserDetails(){
  if(this.userObj.userName.trim() != ''){
    const formData = new FormData();
      formData.append('username',this.userObj.userName);
      formData.append('emailid',this.userObj.emailid);
      this.userService.saveNewUserDetails(formData).subscribe(
       (data) => {
         console.log("user is saved successfully");
       }           
     )
   }
  }       
2 Answers

In saveNewUserDetails() method, do this:

saveNewUserDetails() {
    if (this.email.invalid) {
      // Do Not submit
    } else {
      // Submit
    }
}

OR

I'd still recommend to add [disabled]="email.invalid" to your button:

<button 
  mat-raised-button 
  [disabled]="email.invalid" 
  color="primary" 
  (click)="saveNewUserDetails()">
  Save User
</button>

If you don't want to disable the Save button, but still want to prevent saving, you need to get that information into your save handler. If you simply want the button not to work, you can do it in the template, like this:

<button mat-raised-button color="primary" (click)="email.valid && saveNewUserDetails()">Save User</button>

But if you also want to show a notification, do it in the class (pass the email.valid on the button):

<button mat-raised-button color="primary" (click)="saveNewUserDetails(email.valid )">Save User</button>

saveNewUserDetails(emailValid: boolean)
  if (!emailValid) {
    // show a notification or do something
    return;
  } 
  // otherwise all ok here, keep your logic.
Related