默认类型=电子邮件验证被忽略

时间:2018-10-14 17:42:53

标签: html5 validation angular-material2

我正在构建Angular Material注册表格。输入元素之一是type = email。

预期的行为是,在提交时,如果电子邮件格式不正确,则该表格将无效,并且我将收到默认的浏览器错误,如下所示:

Email Error

Code pen to test desired behavior

但是,这根本不是正在发生的事情。我正在使用Material组件构建表单:

<form class="form" [formGroup]="registerForm" (ngSubmit)="onSubmit()">
    <mat-form-field class="form-full">
        <input matInput placeholder="First Name" style="width:350px" formControlName="firstName" required />
    </mat-form-field>
    <mat-form-field class="form-full">
        <input matInput placeholder="Last Name" style="width:350px" formControlName="lastName" required />
    </mat-form-field>
    <mat-form-field class="form-full">
        <input matInput placeholder="Email" style="width:350px" type="email" formControlName="email" required />
    </mat-form-field>
    <mat-form-field class="form-full">
        <input matInput placeholder="Password" style="width:350px" type="password" formControlName="password" required />
    </mat-form-field>
    <mat-form-field class="form-full">
        <input matInput placeholder="Confirm Password" style="width:350px" type="password" formControlName="confirmPassword" required />
    </mat-form-field>
    <mat-card-actions>
        <button mat-raised-button mat-button color="primary" type="submit">Register</button>
    </mat-card-actions>
</form>

当我刚刚开始构建组件时,我的register.component.ts现在非常基础。我将表单组绑定到我的注册表单,并在onSubmit中释放一些值。

export class RegisterComponent {

  registerForm;

  constructor(private fb: FormBuilder) {
    this.registerForm = fb.group({
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      confirmPassword: '',
    })
  }

  onSubmit() {
    console.log(this.registerForm.value);
    console.log(this.registerForm.valid);
  }

}

我希望registrationForm.valid为false,并且当按下“提交”按钮时会显示浏览器错误,但是这没有发生。当然,我可以自己验证这一点-但是没有得到期望的行为会使我发疯。

以下是结果:

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您应该能够使用EmailValidator指令,只需在输入语法中添加 email 属性即可。

 <input matInput placeholder="Email" style="width:350px" type="email" formControlName="email" email required />

https://angular.io/api/forms/EmailValidator