在角度5中验证同一字段内的电子邮件和电话号码[关闭]

问题描述 投票:-5回答:1

我使用角度6,我有与Gmail相同的登录形式。用户可以输入电子邮件或电话号码。所以我想在客户端验证两者。我将在laravel php的服务器端做。请以最好的方式建议我。

javascript regex angular
1个回答
1
投票

在Angular 4+中,对于客户端验证,使用Reactive表单。

在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 {

  login_form: FormGroup;

  submitForm(){
    for (let v in this.login_form.controls) {
      this.login_form.controls[v].markAsTouched();
    }
    if (this.login_form.valid) {
      // You will get form value if your form is valid
      var formValues = this.login_form.value;    

    }
  }

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

StackBlitz测试:Stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.