【问题标题】:How to validate e-mail with Angular 5如何使用 Angular 5 验证电子邮件
【发布时间】:2019-03-08 17:09:34
【问题描述】:

我想知道如何使用 .com 验证我的电子邮件 我尝试了一切,但我不能,你能帮帮我吗? 我正在总结我已经开发的代码,我对这个角度很陌生,我发现在这个主题上很困难。 如果用户键入 .com,我希望验证电子邮件,但直到现在我只得到基本验证,例如:example @ example。 我希望它是 example@example.com

谢谢

.ts

   import { ActivatedRoute, Params, Router } from "@angular/router";
import { Component, OnInit, Inject, } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';
import { Observable, Subscription } from "rxjs";
import { ModelDataForm } from "./modelDataForm";
import { DOCUMENT } from "@angular/platform-browser";
import 'rxjs/add/operator/filter'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})



export class AppComponent implements OnInit {

  userService: any;
  isTCAccepted: any;
  private subscription: Subscription;
  uri: string;
  ssid: string;
  sessiondId: string;
  ip: string;
  mac: string;
  ufi: string;
  mgmtBaseUrl: string;
  clientRedirectUrl: string;
  req: string;
  userName: string;
  hmac: string;

  name: string;
  email: string;

  //checkbox
  isValidFormSubmitted: boolean = null;




  constructor(@Inject(DOCUMENT) private document: any, private route: ActivatedRoute) {
  }

  //checkbox
  onFormSubmit() {
    this.isValidFormSubmitted = false;
    if (this.userForm.invalid) {
      return;
    }
    this.isValidFormSubmitted = true;
    this.isTCAccepted = this.userForm.get('tc').value;

  }


  ngOnInit() {
    this.route.queryParams
      .filter(params => params.mac)
      .subscribe(params => {
        console.log(params);

        this.ssid = params.ssid;
        this.sessiondId = params.sessionId;
        this.ip = params.ip;
        this.mac = params.mac;
        this.ufi = params.ufi;
        this.mgmtBaseUrl = params.mgmtBaseUrl;
        this.clientRedirectUrl = params.clientRedirectUrl;
        this.req = params.req;
        this.hmac = params.hmac;
      });
  }



  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.pattern('[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}'),
    Validators.email,
  ]);

  nameFormControl = new FormControl('', [
    Validators.required,
  ]);



  userForm = new FormGroup({
    tc: new FormControl('', [(control) => {
      return !control.value ? { 'required': true } : null;
    }])
  });

}

html

<mat-form-field class="hcs-full-width">

  <input matInput placeholder="Nome" [formControl]="nameFormControl" [(ngModel)]="name">
  <mat-error *ngIf="nameFormControl.hasError('required')">
    Nome é
    <strong>requirido</strong>
  </mat-error>
</mat-form-field>


<mat-form-field class="hcs-full-width">
  <input matInput  placeholder="E-mail" [formControl]="emailFormControl" [(ngModel)]="email" >
  <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required') && !emailFormControl.hasError('pattern')">
    Por favor entre com um endereço de e-mail valido
  </mat-error>
  <mat-error *ngIf="emailFormControl.hasError('required')">
    E-mail é
    <strong>requirido</strong>
  </mat-error>
</mat-form-field>

<br>

<div class="checkbox">
  <mat-checkbox class="hcs-full-width" formControlName="tc">
  </mat-checkbox>
  Aceito os termos e condições de uso
  <a data-toggle="collapse" href="#collapseExample">
    ver os termos
  </a>
</div>
<mat-error *ngIf="userForm.get('tc').invalid && isValidFormSubmitted != null && !isValidFormSubmitted" [ngClass]="'error'">
  É necessário aceitar os termos de uso
</mat-error>


<br>

<button mat-button type="submit" class="btn btn-primary btn-lg btn-block button-size" (click)="Logar()">Enviar</button>

<div class="space"></div>

【问题讨论】:

标签: javascript html angular typescript


【解决方案1】:

首选 Angular 提供的电子邮件验证器。

<input type="email" name="email" ngModel email>
<input type="email" name="email" ngModel email="true">
<input type="email" name="email" ngModel [email]="true">

参考:

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

【讨论】:

    【解决方案2】:

    试试这个简单的正则表达式

    if (emailString.match(/[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9A-Z](?:[a-z0-9A-Z]*[a-z0-9A-Z])?\.)+[a-z0-9A-Z](?:[a-z0-9A-Z]*[a-z0-9A-Z])?/)) {
        return null;
      } else {
        return { 'invalidEmailAddress': true };
      }
    

    查看这个 Stackblitz 示例 demo

    【讨论】:

    • 在 stackblitz 中附加了一个示例
    • 希望对您有所帮助。
    【解决方案3】:

    试试正则表达式

    emailFormControl: new FormControl('', Validators.compose([Validators.required, Validators.pattern(/^(([^<>()\[\]\\.,;:\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,}))$/)])),
    

    【讨论】:

    • 更新了我的正则表达式。你现在可以检查一下吗?
    • src/app/app.component.ts(96,25) 中的错误:错误 TS1005:'(' 预期。src/app/app.component.ts(96,36):错误 TS1005 : '=' 预期。src/app/app.component.ts(96,258): 错误 TS1005: ';' 预期。日期: 2018-10-03T13:27:03.313Z - 哈希: 0aa142bd0a2f8edcc4ec - 时间: 546ms
    【解决方案4】:
     Either you can user HTML5 type attribute as email like type="email"
                <div class="form-group">
                  <input class="form-control text-sm-x2 pl-5" placeholder="Email Id" type="email" name="email" [(ngModel)]="userCredentials.email"
                    [disabled]="disableInputs" required email #email="ngModel">
                  <span class="help-block" *ngIf="email?.dirty && email?.errors?.email" style="color:red">
                    <small>Enter a valid email</small>
                  </span>
                </div>
      OR
    use pattern attribute like:
    pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" with default type="text".
    

    【讨论】:

      【解决方案5】:

      您需要更改您的模式,请使用下面的模式作为电子邮件 ID。

      有效的电子邮件 ID 示例:

      sample@sam.com - 有效, sample@sam.in - 有效, sample@sam - 无效。

      pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
      

      【讨论】:

        【解决方案6】:

        试试这个,我们可以用正则表达式模式来验证

        <input type="email" [(ngModel)]="enterEmail" name="myEmail" 
        #myEmail="ngModel" email pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" required>
        

        【讨论】:

          猜你喜欢
          • 2018-08-17
          • 1970-01-01
          • 2014-02-17
          • 2020-02-23
          • 2020-06-18
          • 1970-01-01
          • 1970-01-01
          • 2019-07-05
          • 2019-07-02
          相关资源
          最近更新 更多