首页 > 解决方案 > 如何解决角度 12 中的“TypeError:无法读取 null 的属性“值”错误?

问题描述

在我的 Angular 12 项目中,我创建了一个名为 customValidation 的服务,它应该处理密码模式,并确保在提交表单之前密码和确认密码都匹配。每次运行项目时,我都会从浏览器中收到一条错误消息,指出“TypeError:无法读取 null 的属性‘值’”,指向我创建的服务中的 matchPassword 函数。有人可以告诉我我错过了什么吗?

我的 customValidation.service.ts 代码:

export class CustomvalidationService {
  constructor() {}

  patternValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      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 } {
    let passwordControl = c.get(['passowrd']);
    let confrimPasswordControl = c.get(['cPassword']);

    if (passwordControl!.value !== confrimPasswordControl!.value) {
      return { passwordMismatch: true };
    } else {
    return { passwordMismatch: false };
  }
 }
}

我的 registration.component.ts 文件:

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

  registerForm!: FormGroup;
  submitted = false;

  fname = new FormControl('', [Validators.required]);
  email = new FormControl('', [Validators.required, Validators.email]);
  password = new FormControl('', Validators.compose([Validators.required, this.customvalidator.patternValidator]));
  cPassword = new FormControl('', Validators.compose([Validators.required, this.customvalidator.matchPassword]));
  uPass = new FormControl('', [Validators.required]);


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

  ngOnInit(): void {
    this.registerForm = new FormGroup({});
  }

  // function to submit the registration form

  onRegister() {
    this.submitted = true;
    if (this.registerForm.valid) {
      alert(
        'Form submitted successfully! \n Check the values in the browser console'
      );
      this.authService.SignUp('email.value', 'password.value');
      console.table(this.registerForm.value);
    } else {
      alert('Please fill all fields. Thank you!');
    }
  }
}

标签: angulartypescript

解决方案


验证器函数应该返回一个函数而不是一个对象{ passwordMismatch: true }

您的 matchPassword 应更改为:

 matchPassword(...) {
    return (group: AbstractControl): ValidationErrors | null => {...};
 }

我有一个类似的场景,这是密码验证器:

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

// custom validator to check that two fields match
export function MustMatch(controlName: string, matchingControlName: string) {
  return (group: AbstractControl): ValidationErrors | null => {
    const control = group.get(controlName);
    const matchingControl = group.get(matchingControlName);

    return control.value === matchingControl.value ? null : { notSame: true };
  };
}


推荐阅读