How to know which field has fired cross-validation in FormGroup Validator

634 Views Asked by At

My answer is about cross field validation in Angular Form (check the documentation here cross-field-validation). I would like to know how to find which field's change has fired the form validator when I am inside the validator function (checkAnno, in the example below). This is my code

ngOnInit() {
this.elaborazioneForm = new FormGroup({
  anno: new FormControl('',[Validators.required]),
  modello: new FormControl('',[Validators.required]),
  tipo: new FormControl('', [Validators.required]),
  nProtocollo: new FormControl({ value: null, disabled: true })
},
  {validators: this.checkAnno()}
);
}


checkAnno(): ValidatorFn {
return (formGroup: FormGroup) => {
  if (
    !!formGroup.get('anno').value &&
    !!formGroup.get('modello').value &&
    Math.abs(parseInt(formGroup.get('modello').value, 10) - parseInt(formGroup.get('anno').value, 10)) >= 2
  ) {

here I would like to know which is the control that, with its change, has activated the validation of the form

    formGroup.controls['anno'].setErrors({twoYearsOrMore: true});
    formGroup.controls['modello'].setErrors({twoYearsOrMore: true});
    return { twoYearsOrMore: true };
  } else {
    formGroup.controls['anno'].setErrors(null);
    formGroup.controls['modello'].setErrors(null);
    return null;
  }
};

}

Do you have any ideas how to reach the goal?

1

There are 1 best solutions below

1
Dmytro Demianenko On

If you want to know how to check which field is valid or invalid you can use this

this.form.get('field').invalid

Or this for valid

this.form.get('field').valid

It will work too

this.form.controls.field.invalid