如何在 angular2 中验证新密码和确认密码



>我有2个字段,密码和确认密码。 那么,如何验证两者? .HTML:

<div class="mb-4  col-lg-6">
<label >Password
<span class="required">*</span>
</label>
<input class="form-control" type="password" placeholder="Password"
formControlName="Password">
<control-messages [control]="controls.Password" class="errorMessage"></control-messages>
<div class="errorMessage" *ngIf="validationPassBlank==1">{{errorMessage}}</div>
<div class='required' *ngIf="validationError == 1">{{errorMessage}}</div>
</div>

做这样的事情。

private buildForm(): void {
this.form = this.fb.group({
password: [null, Validators.required],
repeat: [null, Validators.required]
}, {validator: this.checkIfMatchingPasswords('password', 'repeat')});
}

private checkIfMatchingPasswords(passwordKey: string, passwordConfirmationKey: string) {
return (group: FormGroup) => {
const passwordInput = group.controls[passwordKey],
passwordConfirmationInput = group.controls[passwordConfirmationKey];
if (passwordInput.value !== passwordConfirmationInput.value) {
return passwordConfirmationInput.setErrors({notEquivalent: true});
} else {
return passwordConfirmationInput.setErrors(null);
}
};
}

并在表单内的模板中。

<p *ngIf="form.get('repeat')?.errors?.notEquivalent">Passwords did not match</p>
<p *ngIf="form.get('repeat')?.errors?.required">Confirm password is required</p>

您似乎正在使用响应式表单

您需要为Confirm Password再创建一个field,并给出不同的名称作为确认密码

FormGroup中再声明一个字段为"确认密码"并给出。

ConfirmPassword: [''] ,{ validator: [ValidationService.matchingConfirmPasswords] } 

添加检查密码的功能

static matchingConfirmPasswords(passwordKey: any) { 
let passwordInput = passwordKey['value']; 
if (passwordInput.Password === passwordInput.ConfirmPassword) { 
return null; 
} 
else { 
return passwordKey.controls['ConfirmPassword'].setErrors({ passwordNotEquivalent: true }); 
} 
}

在您的 html 中:

<div class="mb-4 col-lg-6"> 
<label > Confirm Password 
<span class="required">*</span> 
</label> 
<input class="form-control" type="password" placeholder=" Confirm Password" 
formControlName="Password"> 
<control-messages [control]="registerForm.controls.ConfirmPassword" class="errorMessage"></control-messages> 
</div> 

最新更新