html - 验证器需要不与自定义验证器一起使用
问题描述
我正在创建一个表单来创建一个新用户。我正在使用自定义验证器来验证密码和确认密码字段值是否匹配。我已将这两个字段设为必填,即它们不能为空。如果密码字段为空并且我尝试创建用户,则会显示错误。但是,当确认密码字段为空时不会引发错误。如果确认密码字段为空,我仍然无法创建用户,但我希望显示错误。我不知道该怎么办。请帮忙。提前致谢。
这是我的模板:
<mat-form-field class="login-field-full-width margin">
<input matInput [type]="!hidePassword ? 'password' : 'text'" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
<mat-error *ngIf="addForm.controls.password.hasError('required')">Password is required</mat-error>
</mat-form-field>
<mat-form-field class="login-field-full-width">
<input matInput formControlName="passwordAgain" placeholder="Confirm password" [type]="!hideConfirmPassword ? 'password' : 'text'" [errorStateMatcher]="passwordsMatcher">
<mat-error *ngIf="addForm.controls.passwordAgain.hasError('required')">Confirm Password is required</mat-error><mat-error *ngIf="addForm.hasError('passwordsNotEqual')">Password Mismatch!</mat-error>
</mat-form-field>
我的自定义 errorStateMatcher:
export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty);
}
}
export function RepeatPasswordValidator(group: FormGroup) {
const password = group.controls.password.value;
const passwordConfirmation = group.controls.passwordAgain.value;
return password === passwordConfirmation ? null : { passwordsNotEqual: true };
}
我的表单组:
passwordsMatcher = new RepeatPasswordEStateMatcher;
this.addForm = this.formBuilder.group({
id: [],
username: ['', Validators.required],
password: new FormControl('', [Validators.required]),
passwordAgain: new FormControl('', [Validators.required]),
}, { validator: RepeatPasswordValidator });
}
onSubmit() {
if (this.addForm.valid) {
this.userService.createUser( this.addForm.value)
.subscribe();
}
}
解决方案
form.submitted
在错误状态匹配器中,如果表单已提交,您可以收听并显示验证。
可能您不想同时显示所需消息和自定义错误消息,因此为自定义验证模板添加检查:
*ngIf="addForm.hasError('passwordsNotEqual') &&
!addForm.hasError('required', 'passwordAgain')"
然后如上所述form.submitted
在自定义错误状态匹配器中添加检查表单:
return ((control && form.form.get('password').value !== control.value && control.dirty)
|| form.submitted)
演示:StackBlitz
推荐阅读
- functional-programming - 如何在方案(N-queens)中从此函数中删除可变性
- python - 如何将用户的消息分配给 discord.py 中的变量?
- android - 有没有办法在兑换代码文本框android中以编程方式自动填充促销代码
- ruby-on-rails - 推送到 heroku 时出现“预编译资产失败”错误
- javascript - 使用 ajax 导入时如何访问较低级别的变量并连接它们
- discord.js - 从特定消息中删除特定成员的反应
- java - 在 Java 中发送 CSRF 身份验证 - Pusher
- r - 在 R 中绑定多个 csv 以输出到 ggplot2 中的图形
- authentication - 使用 GraphQL/HotChocolate 验证登录令牌
- django - 将基于外键的常规类的实例化约束为常规类和抽象类