You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular自定义邮箱验证指令报错:Cannot read properties of null

Angular自定义邮箱验证指令报错:Cannot read properties of null (reading 'includes') 解决方法

错误原因

当输入框未输入内容时,control.value的值为null,此时直接调用字符串方法includes()会触发类型错误。另外原代码的验证逻辑也存在问题:当前逻辑是同时缺少@和.com时才返回错误,但正确的邮箱验证应该是缺少@或者缺少.com时就判定为无效。

修正后的指令代码

修改email-validation.directive.ts,先处理null/空值的情况,同时修正验证逻辑:

import { Directive } from '@angular/core';
import {
  AbstractControl,
  NG_VALIDATORS,
  ValidationErrors,
  Validator,
} from '@angular/forms';

@Directive({
  selector: '[appEmailValidation]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: EmailValidationDirective,
      multi: true,
    },
  ],
})
export class EmailValidationDirective implements Validator {
  validate(control: AbstractControl<any, any>): ValidationErrors | null {
    // 先处理空值/ null 情况,直接返回null(因为已经有required验证)
    const value = control.value;
    if (!value) {
      return null;
    }
    
    const email = value as string;
    // 修正逻辑:缺少@ 或者 缺少.com时,返回invalidEmail错误
    if (!email.includes('@') || !email.includes('.com')) {
      return {
        invalidEmail: true,
      };
    }
    return null;
  }
  constructor() {}
}

模板优化(显示错误提示)

在register.component.html的邮箱输入框中,添加错误提示的显示逻辑:

<mat-form-field appearance="fill" class="width-100">
  <mat-label>Username</mat-label>
  <input appEmailValidation #user="ngModel" required [(ngModel)]="ad.username" name="username" matInput
    placeholder="Enter your username">
  <!-- 添加错误提示 -->
  <mat-hint color="warn" *ngIf="user.invalid && (user.dirty || user.touched)">
    <span *ngIf="user.errors?.invalidEmail">请输入包含@和.com的有效邮箱</span>
    <span *ngIf="user.errors?.required">邮箱不能为空</span>
  </mat-hint>
</mat-form-field>

关键修改点说明

  1. 空值处理:先判断value是否为空,避免null调用字符串方法的错误。
  2. 逻辑修正:将&&改为||,确保只要缺少@或.com其中一个就触发验证错误。
  3. 用户体验优化:在模板中根据不同错误类型显示对应的提示信息,让用户清楚知道哪里出错。

内容的提问来源于stack exchange,提问作者Achintya Dhingra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:56:20