用户名或电子邮件条件验证

Username or email conditional validation

我在 Angular 中有一个忘记密码的表单,我必须在模板驱动的表单中为输入字段“用户名或电子邮件”创建条件验证 如果用户输入@,它会检查电子邮件模式,如果不是,它会检查用户名模式。 现在我想重做,但我想使用反应式方法。 我尝试从互联网上做一些解决方案,但没有用。

任何建议都有帮助

我的模板驱动HTML

<section class="h-100">
  <div class="container h-100">
    <div class="card forgot-password-form-card">
      <div class="card-body p-5">
        <h1 class="fs-4 card-title fw-bold mb-4">Forgot password</h1>
        <form class="form" (ngSubmit)="onSubmit(forgotPasswordForm, forgotPasswordForm.value.usernameEmail)" 
        #forgotPasswordForm="ngForm">
          <div class="mb-3">
            <p>Please enter your username or e-mail.
              <br>You will receive a link to create a new password via e-mail. <br>
            </p>
          </div>
          <div class="mb-5">
            <label for="usernameEmail">Username or e-mail address</label>
            <input id="usernameEmail" type="text" name="usernameEmail" class="form-control" ngModel required
             [pattern]="usernameEmail.value?.includes('@') ? '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$' :
            '[a-zA-Z0-9]{3,}'" #usernameEmail="ngModel" />
            <div class="form-text text-danger" 
            *ngIf="(usernameEmail.touched || usernameEmail.dirty) && usernameEmail.errors?.['required']">
              Username or e-mail is required
            </div>
            <div class="form-text text-danger" *ngIf="(usernameEmail.touched || usernameEmail.dirty)
              && usernameEmail.errors?.['pattern']">
              Username or e-mail address is invalid
            </div>
          </div>
          <div class="d-flex align-items-center">
            <button [disabled]="!forgotPasswordForm.valid" type="submit" class="btn btn-dark
            forgot-password-button col-5 mx-auto">
              Get new password
            </button>
            <button type="button" class="btn btn-light col-5 mx-auto" appBackButton>Back</button>
          </div>
        </form>
      </div>
    </div>
</section>

我的 .ts 文件(内容不多)

import { AbstractControl, AbstractControlOptions, FormBuilder, FormControl, Validators } from '@angular/forms';
import { AppConfig } from 'src/app/_common/configs/app.config';
import { Component } from '@angular/core';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.scss'],
})
export class ForgotPasswordComponent {
  appConfig = AppConfig;
  usernameEmail = new FormControl(null, [
    (c: AbstractControl) => Validators.required(c),
    Validators.pattern()
  ]);
}

您可以定义自己的 custom validator function 并在那里进行检查:

import {
  AbstractControl,
  ValidationErrors,
  ValidatorFn,
  Validators,
} from '@angular/forms';

export function emailOrUsernameValidator(usernameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const usernameValidator = Validators.pattern(usernameRe);
    return control.value?.includes('@')
      ? Validators.email(control)
      : usernameValidator(control);
  };
}

对于电子邮件验证,您可以使用内置的 Validators.email,对于用户名,您可以传递模板中使用的正则表达式:

usernameEmail = new FormControl(null, [
  Validators.required,
  emailOrUsernameValidator(/[a-zA-Z0-9]{3,}/)
]);

要使用响应式表单,您需要放开 ngModel。模板应该是这样的:

<div class="mb-5">
  <label for="usernameEmail">Username or e-mail address</label>
  <input
    id="usernameEmail"
    type="text"
    name="usernameEmail"
    class="form-control"
    required
    [formControl]="usernameEmail"
  />
  <div class="form-text text-danger" *ngIf="usernameEmail.hasError('required')">
    Username or e-mail is required
  </div>
  <div class="form-text text-danger" *ngIf="usernameEmail.hasError('email')">
    The provided e-mail address is invalid
  </div>
  <div class="form-text text-danger" *ngIf="usernameEmail.hasError('pattern')">
    The provided username is invalid
  </div>
</div>