问题描述
我想检查两个字段的值是否相同,这些字段必须通过参数传递给验证函数,我正在这样做,问题是它无法获取字段的值,它显示为空,因为我可以正确且动态地获取值吗?
我的表单生成器,我正在使用Match函数检查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));
}
}
推荐答案
您需要创建自定义Form Group验证器来检查表单控件值的值和检查主题
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