首页 > 解决方案 > 带有引导程序 4 的 Angular 6 - 表单验证电子邮件

问题描述

我有提交电子邮件的表单,我想添加验证,因此不能为空(必需),不能是无效的电子邮件,例如juventusSignedCr7@4.4,等,但是当我将电子邮件添加neymarPleaseStopeDiving到我的输入并单击提交时,不会返回错误并提交数据,只有当我提交空输入时,我才会收到错误消息。电子邮件是必需的

这是我所做的:

更新

组件.ts

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
...............
export class AboutComponent implements OnInit {
  angForm: FormGroup;
constructor(private flashMessages: FlashMessagesService,
    private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      email: ['', Validators.required]
    });
  }

HTML

    <form [formGroup]="angForm" novalidate class="form-element">
   <div class="form-group form-element_email">
              <input type="email" class="form-control" name="email" formControlName="email" #email />
            </div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)"
                class="alert alert-danger">
                <div *ngIf="angForm.controls['email'].errors.required">
                  Email is required.
                </div>

          <div class="form-group">
              <button (click)="addReview(email.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary form-element_btn">Book</button>
            </div>
      </form>

问题

我的代码有什么问题?请在这里帮助新手,谢谢

标签: angularhtmlbootstrap-4

解决方案


Angular 6 提供输入验证器,如电子邮件和必需。

我通常不希望允许me@home格式并总是期望 TLD(如 .com、.net、.org 等)。除了角度email验证器之外,我还添加了我的正​​则表达式pattern以使其工作。

<input type="email" name="email" #emailField="ngModel" pattern="^\S*[@]\S*[.]\S*$" email required />

<div class="help-block m-1" *ngIf="!emailField.valid && (emailField.touched || emailField.dirty)">
  <small>Invalid Email</small>
</div>

email将实现 Angular 的默认电子邮件验证器。

required将使该字段成为必填字段。

pattern="^\S*[@]\S*[.]\S*$"将确保有一个 @ 和一个 . 后跟一个字符串。


推荐阅读