gpt4 book ai didi

angular - 如何检查Angular/Ionic中的两个字段是否相等?

转载 作者:行者123 更新时间:2023-12-03 23:29:07 25 4
gpt4 key购买 nike

我想检查两个字段的值是否相同,这些字段必须通过参数传递给验证函数,我是这样做的,问题是获取不到字段的值,出现null,因为我可以正确动态地获取值吗?

我的表单构建器,我正在使用匹配函数来检查 cell_phone 和确认字段。

this.recharge = this.formBuilder.group({
cell_phone: ['', Validators.required, Validations.match('cell_phone', 'cell_phone_confirmation')],
cell_phone_confirmation: ['', [Validators.required]],
value: ['', Validators.required],
operator_id: ['', Validators.required]
});

在我的函数中,控制台日志为空:
static match(field1: string, field2: string){
return (group: FormGroup) => {
console.log(group.get(field1));
}
}

最佳答案

您需要创建一个自定义的 formGroup 验证器来检查表单控件值的值并检查主题

this.recharge = formBuilder.group({
cell_phone: ['', Validators.required],
cell_phone_confirmation: ['', Validators.required],
},
{
validator: checkMatchValidator('cell_phone', 'cell_phone_confirmation')
}
);

自定义验证器功能
export function checkMatchValidator(field1: string, field2: string) {
return function (frm) {
let field1Value = frm.get(field1).value;
let field2Value = frm.get(field2).value;

if (field1Value !== '' && field1Value !== field2Value) {
return { 'notMatch': `value ${field1Value} is not equal to ${field2}` }
}
return null;
}
}

stackblitz demo 🚀🚀

关于angular - 如何检查Angular/Ionic中的两个字段是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53746285/

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