使用 angular form-b​​uilders 使用正则表达式验证带有白色 space 的电子邮件

validate E-mail with white space with regular expression with angular form-builders

我正在使用表单生成器来验证电子邮件,

TS:

this.registerForm = this.formBuilder.group({
      userName: [
        '',
        [
          Validators.required,
          Validators.email,
          Validators.pattern(
            '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'
          ),
        ],
      ],
    });
  }

get f() {
    return this.registerForm.controls;
  }

validateEmail() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      console.log('Invalid');
      return;
    }
    console.log(this.registerForm.value.userName + ' is a valid Email');
  }

HTML

<form [formGroup]="registerForm" (ngSubmit)="validateEmail()">
  <input
    [ngClass]="{
      'is-invalid': submitted && f.userName.errors,
      blueLine: submitted && f.userName.errors
    }"
    type="text"
    formControlName="userName"
  />
  <button (click)="validateEmail()">Validate</button>
</form>

要求用户可以在电子邮件 ID 末尾输入少量空格,如何在验证电子邮件之前 trim 电子邮件末尾的空格.

例如:

"someone.someone.com " // used 3 white spaces after .com this should trim all the white spaces after .com

stackblitz link : 你可以在这里查看代码实现

您可以使用 trimEnd() 方法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd

首先,您需要删除验证器中的 Validators.email 以允许在表单控件中使用空格。接下来,您需要创建一个自定义验证器,它将 trim 在检查正则表达式模式之前首先结束控制值。然后,将自定义验证器添加为您的验证器之一。

我修改了您创建的 stackblitz 并添加了我的解决方案。

import {
  Component,
  OnInit,
  VERSION
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  email: string;
  registerForm: FormGroup;
  submitted: boolean;

  //Constructor
  constructor(private formBuilder: FormBuilder) {}

  // On init function
  ngOnInit() {
    this.submitted = false;
    this.registerForm = this.formBuilder.group({
      userName: ['', [Validators.required, emailWithWhitespaceValidator]],
    });
  }
  get f() {
    return this.registerForm.controls;
  }

  validateEmail() {
    this.submitted = true;
    if (this.registerForm.invalid) {
      console.log('Invalid');
      return;
    }
    console.log(this.registerForm.value.userName + ' is a valid Email');
  }
}

export function emailWithWhitespaceValidator(control: FormControl) {
  const isValid = control.value
    .trimEnd()
    .match('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$');
  return isValid ? null : {
    isValid: false
  };
}