【发布时间】:2020-10-22 14:52:03
【问题描述】:
我正在研究 Angular 的反应形式。我已经为Password 和Confirm password 设置了字段,如下所示。我正在使用自定义验证来确保 Password 字段与 Confirm password 字段匹配。问题是,尽管在控制台日志记录中,我可以看到表单error 属性将mismatch 设置为true,confirm password 字段仍然有效,因此表单仍然有效。
- 当表单在
errors属性中设置了mismatch属性时,如何确保Confirm Password字段也无效? - 如果我将
passwordMatchValidator附加到confirmPassword(在formcontrol 定义中)而不是在formGroup级别中设置,那么如何设置我的验证?
我的组件模板
<form [formGroup]="registerForm" (ngSubmit)="onRegister()">
<div class="form-group">
<input type="password"
class="form-control" placeholder="Password" formControlName="password">
<div class="invalid-feedback" *ngIf="registerForm.get('password').hasError('required')">Password is required</div>
<div class="invalid-feedback" *ngIf="registerForm.get('password').hasError('minlength')">Password must be at least 5 characters</div>
<div class="invalid-feedback" *ngIf="registerForm.get('password').hasError('maxlength')">Password cannot exceed 8 characters</div>
</div>
<div class="form-group">
<input type="password"
class="form-control" placeholder="Confirm Password" formControlName="confirmPassword">
<div class="invalid-feedback" *ngIf="registerForm.get('confirmPassword').hasError('required')">Password is required</div>
<div class="invalid-feedback" *ngIf="registerForm.hasError('mismatch')">Password must match</div>
</div>
</form>
Css 显示/隐藏错误反馈
.ng-valid{
border: 1px solid green;
}
.ng-invalid.ng-touched + .invalid-feedback{
display: block;
}
我的组件如下所示:
export class RegisterComponent implements OnInit {
registerForm: FormGroup
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.registerForm = this.fb.group({
"password": [null, [Validators.required, Validators.minLength(5), Validators.maxLength(8)]],
"confirmPassword": [null, [Validators.required]]
},{
validators:this.passwordMatchValidator
});
}
passwordMatchValidator(f:FormGroup):{[s:string]:boolean} {
return f.controls['password'].value === f.controls['confirmPassword'].value ? null : { 'mismatch': true }
}
onRegister() {
console.log(this.registerForm)
}
}
【问题讨论】:
标签: angular angular-reactive-forms angular-forms