1

I try to implement a custom Validator for my Angular 9 Form. The validation is a little bit difficult.

Because a couple of fields depends on the selection of a select input.

For example if I select option one of my select, Formfield 3 is required.

But if I select option two, Formfield 5 is required.

That's why I have writte a custom Validator:

export class FormComponent {
  public form: FormGroup = new FormGroup({
    ...
    selectField: new FormControl(null, [Validators.required]),
    ...
    formField3: new FormControl(null, [this.validatorArtAende]),
    formField4: new FormControl(),
    formField5: new FormControl(null, [this.validatorArtAender])
  });

  validator (control: AbstractControl) => {
    if (this.form.value.selectField === 'option1' && control.value.length === 0) {
      return { required: true };
    }
    return null;
  }
}

The issue is that this.form is unknwon (Cannot read property 'form' of undefined). So is there any option to pass the form or the value of a diffrent Control to the custom validator?

2 Answers 2

3

According to the documentation, AbstractControl has a Parent property. You should be able to use that to traverse to your parent FormGroup and then to the selectField inside your validator.

validator (control: AbstractControl) => {
  if (control.parent && control.parent.controls['selectField'] === 'option1' && control.value.length === 0) {
    return { required: true };
  }
  return null;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I still run in the same error. But I added an if around your if, by which i validate if control.parent already exist (if (control.parent) {...} return null). Thank you for your support. I would like to accept your answer when you adjust your code
Updated to make sure the validator checks for a parent before trying to access it.
Rememeber that you need check the controls also when change the selectField. For this you can use some like hte checkControls validator in this SO or subscribe to valueChange or use (input) event and use updateValueAndValidity()
1

Just to update this question as I assume things have moved on in the Angular world as I needed to achieve this very same thing today. You can access all other controls within the form directly from control passed into the validator function using: -

const compareControl = control.get(controlName);

I found using the control.parent approach caused numerous issues with typing and also added additional complexity which is not required.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.