You need to enable JavaScript to run this app. Angular12自定义验证服务报TypeError: Cannot read property 'value' of null如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Angular12自定义验证服务报TypeError: Cannot read property 'value' of null如何解决

问题排查与修复方案

核心错误原因

  • 控件名称拼写错误:CustomvalidationService的matchPassword方法中,将password误写为passowrd,调用c.get()获取不存在的控件会返回null,你使用非空断言!跳过了TS检查,运行时访问value就会抛出空指针错误。
  • 跨字段校验器挂载位置错误:matchPassword是校验两个字段的组级别校验器,你现在把它挂载到cPassword单个FormControl的校验数组里,此时校验器接收的参数c是cPassword控件本身,单个控件没有子控件,调用c.get()必然返回null。
  • FormGroup未正确初始化:你在组件里声明了各个独立的FormControl实例,但ngOnInit里初始化的registerForm是空对象,没有把这些控件注册到表单组中,就算挂载了组校验器也找不到对应控件。
  • 校验器返回值不符合Angular规范:matchPassword校验通过时返回了{passwordMismatch: false},Angular要求校验通过必须返回null,否则会被判定为校验不通过。
  • patternValidator调用错误:patternValidator是工厂方法,需要执行后才会返回校验函数,你在组件里直接传了方法引用没有加(),会导致密码格式校验不生效。

具体修复代码

1. 修复CustomvalidationService

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

export class CustomvalidationService {
  constructor() {}

  patternValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      if (!control.value) {
        return null;
      }
      const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');
      const valid = regex.test(control.value);
      return valid ? null : { invalidPassword: true };
    };
  }

  matchPassword(c: AbstractControl): { [key: string]: any } | null {
    // 修正拼写错误
    let passwordControl = c.get('password');
    let confirmPasswordControl = c.get('cPassword');

    // 提前判断控件是否存在,避免空指针
    if (!passwordControl || !confirmPasswordControl) {
      return null;
    }

    if (passwordControl.value !== confirmPasswordControl.value) {
      return { passwordMismatch: true };
    } 
    // 校验通过返回null
    return null;
  }
}

2. 修复registration.component.ts

import { FormGroup, FormControl, Validators } from '@angular/forms';
// 其余导入省略

export class userRegisterComponent implements OnInit {
  aino: number = new Date().getFullYear();

  registerForm!: FormGroup;
  submitted = false;

  constructor(
    public authService: AuthService,
    private customvalidator: CustomvalidationService
  ) {}

  ngOnInit(): void {
    // 初始化FormGroup时注册所有控件,同时挂载组校验器
    this.registerForm = new FormGroup({
      fname: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required, Validators.email]),
      // patternValidator加()执行获取校验函数
      password: new FormControl('', Validators.compose([Validators.required, this.customvalidator.patternValidator()])),
      cPassword: new FormControl('', Validators.required),
      uPass: new FormControl('', [Validators.required])
    }, {
      // 组校验器挂载在这里
      validators: this.customvalidator.matchPassword
    });
  }

  onRegister() {
    this.submitted = true;
    if (this.registerForm.valid) {
      alert(
        'Form submitted successfully! \n Check the values in the browser console'
      );
      // 修复参数传递错误,取实际表单值
      this.authService.SignUp(this.registerForm.value.email, this.registerForm.value.password);
      console.table(this.registerForm.value);
    } else {
      alert('Please fill all fields. Thank you!');
    }
  }
}

内容的提问来源于stack exchange,提问作者Vintage Farms

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 13:18:03