我正在尝试比较自定义验证器中的两个输入值。如果minValue大于maxValue,则应该会出现错误。
FormGroup:
sumFormGroup = this.formBuilder.group({
from: ['', [Validators.min(0), sumValidator]],
to: ['', [Validators.min(0), sumValidator]]
});
自定义验证器:
function sumValidator (control: AbstractControl):{[key: string]: boolean} | null {
let minValue = control.get(this.sumFormGroup.get('from')).value;
let maxValue = control.get(this.sumFormGroup.get('to')).value;
if(minValue != maxValue){
return {'ageValidator': true}
}
return null;
};
浏览器控制台错误:
ERROR TypeError: Cannot read property 'sumFormGroup' of undefined
at sumValidator in bla.ts
(...)
有人能帮忙吗?谢谢
使验证更加纯粹会有所帮助。此外,我建议对此进行两次验证。
function smallerThan(otherControlName: string) {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (!control.parent) {
return null; // Control is not yet associated with a parent.
}
const thisValue = control.value;
const otherValue = control.parent.get(otherControlName).value;
if (thisValue < otherValue) {
return null;
}
return {
'smallerthan': true
}
};
}
function greaterThan(otherControlName: string) {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (!control.parent) {
return null; // Control is not yet associated with a parent.
}
const thisValue = control.value;
const otherValue = control.parent.get(otherControlName).value;
if (thisValue > otherValue) {
return null;
}
return {
'greaterthan': true
}
};
}
用法:
sumFormGroup = this.formBuilder.group({
from: ['', [Validators.min(0), smallerThan('to')]],
to: ['', [Validators.min(0), greaterThan('from')]]
});
也许您还需要考虑到这些值可能不相等,但您可以轻松地再创建两个名为smallerThanOrEquals
和greaterThanOrEquals
的验证器。
如果您希望同步验证,可以尝试在组件中以以下方式进行:
ngOnInit() {
// Example in the init, but make sure this.sumFormGroup is already created.
this.sumFormGroup.get('from').valueChanges.subscribe(() => this.sumFormGroup.get('to').updateValueAndValidity({ onlySelf: true, emitEvent: false }));
this.sumFormGroup.get('to').valueChanges.subscribe(() => this.sumFormGroup.get('from').updateValueAndValidity({ onlySelf: true, emitEvent: false }));
}