首页 > 解决方案 > 在角度 5 中验证同一字段中的电子邮件和电话号码

问题描述

我正在使用 Angular 6,并且我的登录表单与 Gmail 相同。喜欢的用户可以输入电子邮件或电话号码。所以我想在客户端验证两者。我将在 laravel php 的服务器端做。请用最好的方法给我建议。

标签: javascriptregexangular

解决方案


在 Angular 4+ 中,对于客户端验证,请使用反应式表单。

在您的 html 中使用表单

<form [formGroup]="login_form" (submit)="submitForm()">
  <input class="form-control" type="email" placeholder="Enter email" formControlName="email" />
  <span class="text-danger" *ngIf="login_form.controls['email'].hasError('required') && (login_form.controls['email'].dirty || login_form.controls['email'].touched)">Email address is required</span>
  <span class="text-danger" *ngIf="login_form.controls['email'].hasError('email') && (login_form.controls['email'].dirty || login_form.controls['email'].touched)">Please enter valid email address</span>
    
  
  <input class="form-control" type="password" placeholder="Enter Password" formControlName="password" />
  <span class="text-danger" *ngIf="login_form.controls['password'].hasError('required') && (login_form.controls['password'].dirty || login_form.controls['password'].touched)">Password is required</span>
  
  
  <button class="btn btn-block btn-primary mt-lg" type="submit">Login</button>
</form>

在您的组件中使用以下代码

// First install this package using below cli command
// npm install ng2-validation --save

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';

export class YourComponent {

  public login_form: FormGroup;
  
  public submitForm(){        
    if (this.login_form.valid) {
      // You will get form value if your form is valid
      var formValues = this.login_form.value;    
      ....
    } else {
      // For Angular 4,5.
      for (let v in this.login_form.controls) {
         this.login_form.controls[v].markAsTouched();
      }

      // For Angular 6+ versions.
      this.login_form.markAllAsTouched();
    }
  }

  constructor(fb: FormBuilder) {
    this.login_form = fb.group({
      'email': [null, Validators.compose([Validators.required, CustomValidators.email])],
      'password': [null, Validators.required],
    });
  }

StackBlitz 测试:Stackblitz


推荐阅读