我想检查两个字段的值是否相同,这些字段必须通过参数传递给验证函数,我这样做是,问题是它无法获取该字段的值,出现为空,因为我可以正确,动态地获取值吗?
我的表单生成器,我正在使用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));
}
}
答案 0 :(得分:2)
您可以尝试这样。
this.recharge = this.formBuilder.group({
cell_phone: ['', Validators.required],
cell_phone_confirmation: ['', [Validators.required]],
value: ['', Validators.required],
operator_id: ['', Validators.required]
},{ validator: Validations.match });
static match(c: AbstractControl){
const cellphone = c.get('cell_phone');
const cellphoneconfirm = c.get('cell_phone_confirmation');
}
答案 1 :(得分:2)
我将使用root属性访问cell_phone_validator
控件
cell_phone: ['', [Validators.required, this.cellPhoneValidator]]
private cellPhoneValidator(control: AbstractControl) {
if (control.root.get('cell_phone_confirmation') {
return control.root.get('cell_phone_confirmation').value !== control.value ?
{ cellPhoneValidator: { value: control.value } } : null;
}
}
编辑:,您想将其用于任何字段,所以让它变得通用
cell_phone: ['', [Validators.required, Validations.matchValidator('cell_phone_confirmation')]],
cell_phone_confirmation: ['', [Validators.required, Validations.matchValidator('cell_phone')]]
private matchValidator(controlValidationName: string): ValidatorFn {
return (control: AbstractControl) => {
const controlValidation = control.root.get(controlValidationName);
if (!controlValidation) {
return null;
}
return controlValidation.value !== control.value ?
{ matchValidator: { value: control.value } } : null;
}
}
答案 2 :(得分:2)
您需要创建一个自定义的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;
}
}