当我显示formControl的验证错误时,我发现我无法显示自定义异步验证器捕获的错误。
我现在试图在Ui中显示错误是这样的:
<span
class="warn"
*ngIf="signUpForm.get('repeatPassword').touched && signUpForm.hasError('matchingPasswords')">
Passwords don't match
</span>
但是显然hasError()不能在async验证器上工作。
注意a:我使用的是响应式表单方法。
注意b: asynn验证器(matchingPasswords)工作正常,当它捕获错误时,表单被禁用。
编辑:
这是我使用的自定义验证器
matchingPasswords(AC: FormControl) {
return new Promise( resolve => {
let password = AC.parent.controls['password'].value; // to get value in input tag
let confirmPassword = AC.value; // to get value in input tag
if(password === confirmPassword) {
return resolve(null); // All ok, passwords match!!!
} else {
return resolve({"no_match": true})
}
});
}
下面是我如何将它添加到我的表单控件:
'repeatPassword': new FormControl(null,
[Validators.required,
Validators.minLength(6)],
this.matchingPasswords.bind(this))
我不知道为什么您的自定义验证器不起作用,您应该将其添加到您的问题中。实际上,您不需要为这个想法定制验证器。你可以比较formcontrol之间的值。下面是一个如何在html文件中访问FormControl的示例。
在typescript文件中:
export class myComponent implements OnInit {
public password: FormControl = new FormControl('', [Validators.required]);
public passwordConfirmation: FormControl = new FormControl('', [Validators.required]);
public fg: FormGroup;
public constructor() { }
public ngOnInit(): void {
this.fg = new FormGroup({
email: this.password,
emailConfirmation: this.passwordConfirmation
});
}
}
在你的HTML文件中:
<div>
<label for="password" [ngClass]="{'text-danger': !password.valid && password.touched}">Password:</label>
<input id="password" class="form-control" type="password" [ngClass]="{'is-invalid': !password.valid && password.touched}" formControlName="password">
<small *ngIf="!password.valid && password.touched" class="text-danger">Password required</small>
</div>
<div>
<label for="password-confirmation" [ngClass]="{'text-danger': !passwordConfirmation.valid && passwordConfirmation.touched}">Password confirmation:</label>
<input id="password-confirmation" class="form-control" type="text" [ngClass]="{'is-invalid': !passwordConfirmation.valid && passwordConfirmation.touched}" formControlName="passwordConfirmation">
<small *ngIf="(password.value !== passwordConfirmation.value) && passwordConfirmation.touched" class="text-danger">Password does not match</small>
</div>