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");
}
)
}
}