gpt4 book ai didi

angular - 在 Angular 中比较自定义验证器中的值

转载 作者:行者123 更新时间:2023-12-05 03:51:26 24 4
gpt4 key购买 nike

我正在尝试比较自定义验证器中的两个输入值。如果 minValue 大于 maxValue,应该会出错。

表单组:

    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')]]
});

也许您还需要考虑到值可能不相等,但您可以轻松地创建另外两个验证器,分别称为 smallerThanOrEqualsgreaterThanOrEquals

如果你想同步验证,你可以尝试在你的组件中按以下方式进行:

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 }));
}

关于angular - 在 Angular 中比较自定义验证器中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62890714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com