Access multiple form control values from the same formgroup from a customValidator

Hi!

I’m trying to implement a reactive form with a formgroup of 2 elements and a validator to access the 2 elements simultaneously. How can this be achieved?

eg:
this.formBuilder.group({
var1: [’’, [Validators.required, customValidator]],
var2: [’’, [Validators.required, customValidator]]
});

The use case scenario is var1 must never be greater than var2 and var2 must never be less than var1.

Thank you.

export const customValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {

    if (!control.parent || !control) { return null; }

    const var1 = control.parent.get('var1');

    const var2 = control.parent.get('var2');

    if (!var1 || !var2 || var1.value === '' || var2.value === '') { return null; }

    if (var1.value >= var2.value) { return null; }

    return { customValidator: true };

};

I think you might use it like this.

1 Like

Thank you for your input. Using control.parent I can indeed reach the other variables and that I was missing.

With my standard disclaimer that nobody need care a single iota about my opinion, I would avoid this strategy on philosophical grounds.

This looks to me like a “silent dependency”. If you reorganize the structure of the form, that validator will break.

So IMHO, parent should be off-limits. Using it is an indicator that the validator is on the wrong component, and needs to be higher up. There is an example of what I would consider a much more robust way of handling this in the official Angular docs on cross-field validation. The validator should be on the group, not on one of the individual group members.