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

template:

<form [formGroup]="dialogForm">
  <div class="row">
    <div class="lbl-col">
        <label for="reason">Reason<span class="required-star">*</span></label>
    </div>
  <div class="col">
    <textarea
        id="reasonForChange"
        formControlName="reasonForChange"
        name="reasonForChange"
        type="text"
        [(ngModel)]="selectedReasonText"
        [ngClass]="{invalid: dialogForm.get('File').invalid}"
    >
    </textarea>
  </div>
  </div>
    <div class="row">
        <div class="lbl-col"></div>
        <div class="col">
            <input
                type="file"
                id="reasonFile"
                formControlName="File"
                (change)="onFileChange($event)"
            />
        </div>
    </div>
</form>
[...]
// submit button
<button
  class="primary-button"
  label="update status"
  (click)="update()" // a POST nothing more.
  [disabled]="dialogForm.invalid"
></button>

and in my controller:

    constructor(
        private fb: FormBuilder
    ) {
        this.dialogForm = this.fb.group({
            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:

    constructor(
        private fb: FormBuilder
    ) {
        this.dialogForm = this.fb.group({
            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>
    </div>

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 https://angular.io/guide/form-validation#adding-cross-validation-to-template-driven-forms

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.