Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am wanting to check if the values of two fields are the same, these fields must be passed by parameters to the validation function, I am doing this, the problem is that it can not get the value of the field, it appears null, as Can I get the values correctly and dynamically?

My form builder, I'm using the match function to check the cell_phone and confirmation fields.

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

In my function, console log is null:

static match(field1: string, field2: string){
  return (group: FormGroup) => {
    console.log(group.get(field1));
  }
}
like image 463
Vinicius Aquino Avatar asked Nov 16 '25 16:11

Vinicius Aquino


1 Answers

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

like image 97
Muhammed Albarmavi Avatar answered Nov 19 '25 08:11

Muhammed Albarmavi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!