【发布时间】:2018-09-21 09:37:33
【问题描述】:
@angular/forms:6.1.7
我正在尝试创建一个自定义验证器来检查 2 个 formControl 是否不一致。
当关注official angular documentation 时,将值输入到以下两种形式之一时出现错误:
Uncaught Error: Expected validator to return Promise or Observable.
at toObservable (forms.js:596)
at Array.map (<anonymous>)
at FormControl.asyncValidator (forms.js:584)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runAsyncValidator (forms.js:2454)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2427)
at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.FormControl.setValue (forms.js:2764)
at updateControl (forms.js:1699)
at DefaultValueAccessor.onChange (forms.js:1684)
at DefaultValueAccessor.push../node_modules/@angular/forms/fesm5/forms.js.DefaultValueAccessor._handleInput (forms.js:741)
at Object.eval [as handleEvent] (ChangePasswordComponent.html:13)
在这种情况下,Angular 似乎试图找到 asyncValidator,而不是我期望的 sync 版本。
值得一提的是,我还尝试返回一个Observable<ValidationErrors | null>,它给了我相同的错误输出。
验证器:
import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export const passwordMatchValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
if (!password || !confirmPassword) {
return null;
}
return password === confirmPassword ? null : { passwordMismatch: true };
};
实施:
this.formGroup = this.formBuilder.group(
{
password: ['', Validators.required, Validators.minLength(6)],
confirmPassword: ['', Validators.required, Validators.minLength(6)]
},
{
validators: passwordMatchValidator
}
问题
如何创建自定义同步跨字段验证器?
旁边的问题
是否可以将 formControl 名称 传递给函数而不是对其进行硬编码?
更新:最终解决方案
import { FormGroup, ValidationErrors, ValidatorFn } from "@angular/forms";
export const matchValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
return (control: FormGroup): ValidationErrors | null => {
const firstControlValue = control.get(firstControlName).value;
const secondControlValue = control.get(secondControlName).value;
if (!firstControlValue || !secondControlValue) {
return null;
}
return firstControlValue === secondControlValue ? null : { mismatch: true };
}
};
实施:
this.formGroup = this.formBuilder.group(
{
password: ['', [Validators.required, Validators.minLength(6)]],
confirmPassword: ['', [Validators.required, Validators.minLength(6)]],
currentPassword: ['', Validators.required]
},
{
validator: matchValidator('password', 'confirmPassword')
}
【问题讨论】:
标签: angular angular-reactive-forms angular-forms