Rem*_*yaJ 19 angular2-forms angular
我需要使用反应式表格angular2来检查密码和确认密码字段是否具有相同的值.我确实在这里看到了很多答案,Angular 2表格验证了重复密码,比较验证器中的字段和angular2,但似乎没有人对我有用.有人请帮忙."这个"在我的验证函数中是未定义的: (.分享我的代码,
this.addEditUserForm = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
title: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
confirmPass: ['', [Validators.required, this.validatePasswordConfirmation]]
});
validatePasswordConfirmation(group: FormGroup): any{
let valid = true;
// if (this.addEditUserForm.controls.password != this.addEditUserForm.controls.confirmPass) {
// valid = false;
// this.addEditUserForm.controls.confirmPass.setErrors({validatePasswordConfirmation: true});
// }
return valid;
}
Run Code Online (Sandbox Code Playgroud)
Rem*_*yaJ 33
这最终对我有用 -
this.addEditUserForm = this.builder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
title: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required],
confirmPass: ['', Validators.required]
},{validator: this.checkIfMatchingPasswords('password', 'confirmPass')});
checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
let passwordInput = group.controls[passwordKey],
passwordConfirmationInput = group.controls[passwordConfirmationKey];
if (passwordInput.value !== passwordConfirmationInput.value) {
return passwordConfirmationInput.setErrors({notEquivalent: true})
}
else {
return passwordConfirmationInput.setErrors(null);
}
}
}
Run Code Online (Sandbox Code Playgroud)
AJT*_*T82 24
最好的办法是有形式的组,在这里我们有一个自定义的验证检查的形式,组内嵌套组password和confirmPass,因此无论是字段改变时,验证被解雇,因为以前它仅火灾时,confirmPass现场被修改.
所以在外部formgroup中做这样的事情:
// ...
passwords: this.fb.group({
password: ['', [...]],
confirmPass: ['', [...]]
}, {validator: this.checkPasswords}) // add a validator for the whole group
// ...
Run Code Online (Sandbox Code Playgroud)
然后验证器可能如下所示:
checkPasswords(group: FormGroup) { // here we have the 'passwords' group
let pass = group.get('password').value;
let confirmPass = group.get('confirmPass').value;
return pass === confirmPass ? null : { notSame: true }
}
Run Code Online (Sandbox Code Playgroud)
然后可以像这样显示验证错误:
*ngIf="addEditUserForm.hasError('notSame', 'passwords')"
Run Code Online (Sandbox Code Playgroud)
当然,您不需要拥有嵌套组,但每次表单发生任何更改时,最好不要使用自定义验证程序.这样,只有在此内部表单组发生更改时才会触发它.
| 归档时间: |
|
| 查看次数: |
26495 次 |
| 最近记录: |