请帮助理解。我正在尝试为反应形式编写自定义验证器。
零件:
private form: FormGroup;
ngOnInit() {
const this_ = this;
this.form = new FormGroup({
'email': new FormControl(null, [Validators.required, Validators.email]),
'password': new FormControl(null, [Validators.required, Validators.minLength(6)]),
'password2': new FormControl(null, [Validators.required, Validators.minLength(6), this_.comparePasswords]),
'name': new FormControl(null, [Validators.required]),
'agree': new FormControl(false, [Validators.requiredTrue])
});
}
comparePasswords(c: FormControl) {
console.log(c);
const hashStr = Md5.hashStr(c.value.password);
const hashStr2 = Md5.hashStr(c.value.password2);
console.log(hashStr, hashStr2);
return (hashStr === hashStr2) ? null : {
comparePasswords: {
valid: false
}
};
}
您需要连接的所有导入。加载页面后,浏览器控制台会立即显示表单对象,其中value对象为null。
我无法检查函数comparePasswords()。
控制台显示如下:
错误TypeError:无法读取null的属性“password”
将null
改为""
this.form = new FormGroup({
'email': new FormControl("", [Validators.required, Validators.email]),
'password': new FormControl("", [Validators.required, Validators.minLength(6)]),
'password2': new FormControl("", [Validators.required, Validators.minLength(6), this_.comparePasswords]),
'name': new FormControl("", [Validators.required]),
'agree': new FormControl(false, [Validators.requiredTrue])
});
除了给null
初始值,你在formcontrol上设置你的自定义验证器,所以你在自定义验证器中实际得到的只是formcontrol password2
,而不是整个表单组。
因此,我将自定义验证器放在formgroup级别,或者更好的是,为密码创建一个嵌套的formgroup并为其应用验证器。为什么?因为如果您在整个表单上应用验证器,只要表单发生任何更改,它就会被触发。但是在这个示例中,我将它应用于整个表单以及缩小您的代码。在表单组级别(嵌套或不嵌套)上应用自定义验证器的优点还在于检查输入。由于您的验证器位于您的问题中,因此只有当password2
字段发生更改时,才会检查password
是否与password2
匹配。那么如果在修改password
之后修改password2
字段会发生什么,则不会显示错误,并且表单被认为是有效的。
所以建立形式如下:
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.form = this.fb.group({
password: ['', [Validators.required, Validators.minLength(6)]],
password2: ['', [Validators.required, Validators.minLength(6)]],
},{validator: this.comparePasswords});
}
然后您的自定义验证器将如下所示:
comparePasswords(c: FormGroup) {
const hashStr = Md5.hashStr(c.controls.password.value);
const hashStr2 = Md5.hashStr(c.controls.password2.value);
return (hashStr === hashStr2) ? null : { notSame: true };
}
你可以比较c.controls.password.value
和c.controls.password2.value
但是因为你使用Md5
,我只是在这里使用这些值。另请注意,我们只是发送一个包含您选择的自定义错误的对象,如果密码不匹配,请输入notSame
。
并显示您可以执行的错误消息:
<div *ngIf="form.hasError('notSame')">Passwords do not match!</div>
你修改过的StackBlitz