angular - 如何在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>
推荐阅读
- jmeter - 如何在 Pepper-Box 纯文本配置中打印迭代号?
- macos - 使用为 MacOS 构建的框架的 Catalyst 应用程序
- php - 将优惠券添加到现有的 WooCommerce 订阅
- c# - 在 WebAssembly 上使用 Uno Platform 和 Xamarin.Forms 时出现“包含重复的 'EmbeddedResource' 项目”
- django - Django oracle 数据库连接
- r - 使用“*”作为字符时,为什么不能将 Reduce 与 paste 结合使用?
- azure-devops - DevOps,管理 IIS 网站任务,netsh 添加 sslcert,失败并出现错误 1312
- c - 如何将未命名的 Posix 信号量写入共享内存?
- java - TLS 客户端身份验证 | Sectigo CA | 爪哇
- database - 将 Blast+ 与本地数据库一起使用