How to validate Angular fromgroup input based on the value of a 2nd input in the form in Angular?

I have a [formGroup] in Angular version8 app.
I am trying to validate the form based on these simple rules:

  1. if a file is uploaded (includes just choosing any file with the button) then the Reason input is NOT required, else
  2. if a file has not been chosen (ie ‘choose file’ has no value) then a Reason must be provided for form validation to pass.

File upload is optional if a Reason text is provided.
How do I check inside the Reason textArea that a file has been chosen? I simply can’t seem to write a validation statement using that ngClass


<form [formGroup]="dialogForm">
  <div class="row">
    <div class="lbl-col">
        <label for="reason">Reason<span class="required-star">*</span></label>
  <div class="col">
        [ngClass]="{invalid: dialogForm.get('File').invalid}"
    <div class="row">
        <div class="lbl-col"></div>
        <div class="col">
// submit button
  label="update status"
  (click)="update()" // a POST nothing more.

and in my controller:

        private fb: FormBuilder
    ) {
        this.dialogForm ={
            chooseStatus: [null, Validators.required],
            reasonForChange: [null, Validators.required],
            File: [null],

Using [ngClass]="{invalid: dialogForm.get('File').invalid}" or variations of it, it doesn’t appear to check formControlName="File" but instead checks itself, ‘reasonforChange’.

I have also tried the croos crossValidation template from Ang docs.
Extend the Formbuilder:

        private fb: FormBuilder
    ) {
        this.dialogForm ={
            chooseStatus: [null],
            reasonForChange: [null],
            File: [null],
        }, {validators: crossFormValidator}

and provide

export const crossFormValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
    const reasonForChange = control.get('reasonForChange');
    const file= control.get('File');
    return attachment && reasonForChange && attachment.value !== '' ? { crossValid: true } : null;

but that errors on this line in my template

    <div *ngIf="dialogForm.errors?.['crossValid'] && (dialogForm.dirty)" class="form-validation-warning">
        <span class="warning-label">* Required</span>

at Parser Error: Unexpected token [, expected identifier or keyword at column 20 in [dialogForm.errors?.['crossValid'] && (dialogForm.dirty)]
Even though that is taken almost verbatiim from the angular docs at

Source: JavaSript – Stack Overflow

November 23, 2021
Category : News
Tags: angular | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.