如何解决 angular 12 中的“TypeError:无法读取 null 的属性‘value’”错误?
2021-08-11
1196
在我的 angular 12 项目中,我创建了一个名为 customValidation 的服务,该服务应处理密码模式,并确保在提交表单之前密码和确认密码都匹配。每次运行该项目时,我都会从浏览器中收到一条错误消息,提示“TypeError:无法读取 null 的属性‘value’”,指向我创建的服务中的 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!');
}
}
}
2个回答
在服务中声明
passwordControl
时,您的
password
拼写错误。
let passwordControl = c.get(['passowrd']);
应更改为
let passwordControl = c.get(['password']);
Joshua McCarthy
2021-08-11
验证器函数应返回一个
函数
,而不是对象
{ 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 };
};
}
huan feng
2021-08-11