如何在不按下按钮的情况下(没有表格)如何验证电子邮件地址中包含@符号和点。我将不胜感激。
<mat-form-field class="example-full-width">
<input matInput placeholder="Favorite food" value="Sushi">
</mat-form-field>
答案 0 :(得分:2)
您可以使用模式并定义正则表达式来验证电子邮件地址,
<input matInput placeholder="Favorite food" [(ngModel)]="enterEmail" name="myEmail" pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" required>
答案 1 :(得分:1)
我正在使用Angular 8,它的指令为EmailValidator。
与ngModel一起使用,如下所示:
<input type="email" name="email" ngModel email>
<input type="email" name="email" ngModel email="true">
<input type="email" name="email" ngModel [email]="true">
答案 2 :(得分:0)
您也可以通过这种方式进行验证
在您的模板(.html文件)中:
<form
[formGroup]="userForm"
#formDirective="ngForm"
(ngSubmit)="onFormSubmit()"
>
<div class="form-control">
<mat-form-field appearance="outline" class="form-field">
<mat-label>Email Address</mat-label>
<input
type="text"
matInput
formControlName="email"
class="form-input-field"
pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}"
/>
<mat-error *ngIf="userForm.get('email').hasError('required')"
>Email is required</mat-error
>
<mat-error *ngIf="userForm.get('email').hasError('email')"
>Please enter a valid email address
</mat-error>
</mat-form-field>
</div>
</form>
在您的组件(.ts文件)中:
userForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
});