Angular 6 with bootstrap 4 - 表单验证电子邮件

标签 angular html bootstrap-4

我有提交电子邮件的表格,我想添加验证,因此不能为空(必需),不能为无效电子邮件,例如 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>

Question

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

最佳答案

您还可以在输入标签中为电子邮件字段使用正则表达式,就像这样

<input type="email" class="form-control info" placeholder="Email" formControlName="email" (ngModelChange)="onChange($event)">

像这样每次用户在里面输入时调用一个函数,然后在你的 Ts 文件中,你声明你放在 html 中的输入标签中的函数

onChange(newValue) {
    const validEmailRegEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (validEmailRegEx.test(newValue)) {
        this.validEmail = true;
    }else {
      this.validEmail = false;
    }

  }

只是不要忘记在文件顶部声明变量 validEmail

validEmail:boolean = false

常量 validEmail 是你声明正则表达式的地方,我放的那个我非常适合电子邮件验证,方法 test 是你比较表达式的地方字符串,该方法返回 true 或 false 之后,在您的 html 按钮标签中出现类似这样的内容。

<button type="submit" class="btn btn-primary btn-block logBtn" [disabled]="!validEmail">ACCEDER</button>

我喜欢这种方式,因为我可以完全控制每个输入标签中我想要的内容

关于Angular 6 with bootstrap 4 - 表单验证电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181412/

相关文章:

css - 冲突!CSS 中的重要声明

html - 调整图像大小以适合 div(作为背景)的最佳方式

angular - 在当前版本的 Angular2 中,我们可以在另一个组件中使用一个组件吗?

javascript - 为了将轮播集成到 Bootstrap 页面中,我必须做什么

javascript - Angular Observable 不执行 put 调用

html - 为什么 fixed navigation box-shadow 在 Firefox 和 IE 中不能正常显示?

javascript - 如果 <body> 有类,如何防止加载页面

css - Bootstrap 导航栏元素之间的响应空间

Angular 12 typescript 上传文件错误415不支持的媒体类型

javascript - 如何在 Angular 2中将参数传递给POST方法