我有一个自定义验证程序来检查重新输入确认
import { AbstractControl } from '@angular/forms';
export function RetypeConfirm(confirmpassword: string) {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (control.value !== confirmpassword) {
return { 'mismatch': true };
}
return null;
};
}
我的打字稿文件
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { RetypeConfirm } from 'app/validators/retype-confirm.validator';
passwordChangeForm: FormGroup;
constructor(private fb: FormBuilder){
this.passwordChangeForm = this.fb.group({
newPassword: ["", [Validators.required, Validators.pattern(RegEx.STRONG_PASSWORD)]],
confirmpassword: ["", [Validators.required, RetypeConfirm(***I want to pass passwordChangeForm.controls['newPassword'].value here**** )]]
});
}
我需要将this.passwordChangeForm.controls['newPassword'].value
传递给RetypeConfirm自定义验证器
答案 0 :(得分:4)
该函数获取密码字段并与确认密码进行比较
function RetypeConfirm(newpassword: string): ValidatorFn {
return (control: FormControl) => {
if (!control || !control.parent) {
return null;
}
return control.parent.get(newpassword).value === control.value ? null : { mismatch: true };
};
}
您可以直接从组中传递密码的值
this.signUpForm = this.fb.group({
newpassword: ['', [Validators.required]],
confirmPassword: ['', [
Validators.required,
RetypeConfirm('newpassword')
]]
});
还有html
<form [formGroup]="signUpForm">
<label>New Password</label>
<input formControlName="newpassword" />
<br>
<label> Confirm Password</label>
<input name="confirmPassword" formControlName="confirmPassword"/>
<span *ngIf=" signUpForm.get('confirmPassword').errors?.mismatch">Password Confirmation must match password</span>
</form>
工作Stackblitz 。希望对您有帮助。
答案 1 :(得分:1)
您不必强行通过它,因为SDK允许您使用 AbstractControl 的父字段为您提供所需的内容,从而为您提供 FormGroup参考,方法如下:
export const RetypeConfirmValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
if (!control.parent || !control) {
return null;
}
const newPassword = control.parent.get('newPassword'); // The new password
const confirmpassword = control.parent.get('confirmpassword'); // The retyped password
if (!newPassword || !confirmpassword){
return null;
}
if (confirmpassword.value === ''){
return null;
}
if (newPassword.value === confirmpassword.value){
return null;
}
return { 'mismatch': true };
};
答案 2 :(得分:0)
这种方式对我有用
import { FormControl } from '@angular/forms';
export function RetypeConfirm(confirmpassword: string) {
return (control: FormControl): { [key: string]: boolean } | null => {
if (!control || !control.parent) {
return null;
}
if (control.value !== control.parent.get(confirmpassword).value) {
return { 'mismatch': true };
}
return null;
};
}
在您的打字稿文件中
this.passwordChangeForm = this.fb.group({
newPassword: ["", [Validators.required, Validators.pattern(RegEx.STRONG_PASSWORD)]],
confirmpassword: ["", [Validators.required, RetypeConfirm('newPassword')]],
});
如何传递该值:RetypeConfirm('newPassword')