How to check if two fields are equal in Angular / Ionic?

社会主义新天地 提交于 2019-12-06 06:14:44

You need to create a custom formGroup validator to check the value of the form controls values and check theme

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

Custom Validator function

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 🚀🚀

You can try like this.

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

I'd use root property to access to cell_phone_validator control

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

}

EDIT : you want to use it for any field, so let's make it general

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;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!