我有一个带有电子邮件表单字段的 angular6 表单。
电子邮件表单字段具有电子邮件验证功能,可在电子邮件无效时正确显示错误消息。但是如果我点击“保存”按钮,表格仍然会被保存。如何显示错误消息,但不在单击时保存用户?
重要的要求是我不想禁用“保存”按钮。
用户.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>
用户.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");
}
)
}
}
最佳答案
在 saveNewUserDetails()
方法中,执行以下操作:
saveNewUserDetails() {
if (this.email.invalid) {
// Do Not submit
} else {
// Submit
}
}
或
我仍然建议将 [disabled]="email.invalid"
添加到您的按钮:
<button
mat-raised-button
[disabled]="email.invalid"
color="primary"
(click)="saveNewUserDetails()">
Save User
</button>
关于angular - Angular 6 中的电子邮件验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008598/