简体   繁体   中英

Angular 8: File validation error messages appear before uploading file

I have a reactive form in Angular 8 to upload a file. I have used a custom validator and also built in validator. The issue is that, when I click on the upload button before the file is selected for upload/uploaded both the validation error messages appear. I also, tried using updateOn: blur option but still the validation error messages appear before I have the chance to upload file. How to fix the issue.

<form [formGroup]="uploadForm" (ngSubmit)="onSubmit()">
    <div>
        <label for="fileInput" class="mandatory">Upload File</label>
        <input type="file" id="fileInput" required formControlName="fileInput" name="fileInput" (change)="onFileUpload($event)">
        <div class="input-error-alert" *ngIf="fileInput.invalid  && (fileInput.dirty || fileInput.touched)">
            <div *ngIf="fileInput.errors.required">Please upload file.</div>
            <div *ngIf="fileInput.errors.invalidFile">Please upload Excel file.</div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary" [disabled]="!uploadForm.valid">Submit</button>
</form>

component
swaggerForm = this.formBuilder.group({
    swaggerFile: ['', [Validators.required, fileTypeValidator()]]
});

Also tried, 

swaggerForm = this.formBuilder.group({
    swaggerFile: ['', {validators: [Validators.required, fileTypeValidator()], updateOn: 'blur'}]
});


file-validation.directive.ts
export function fileTypeValidator(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        let fileName = control.value;
        let ext = fileName.substring(fileName.lastIndexOf('.') + 1);
        return (ext === 'xls' || ext === 'xlsx') ? null : {'invalidFile': true};
    };
}

The Error you are getting is because once you click on fileInput field, the fileInput gets dirty and as file is required os by default fileInput.invalid is true.

One Solution I can think of is

<div class="input-error-alert" *ngIf="isFileUploaded && fileInput.invalid  && (fileInput.dirty || fileInput.touched)">
  <div *ngIf="fileInput.errors.required">Please upload file.</div>
  <div *ngIf="fileInput.errors.invalidFile">Please upload Excel file.</div>
</div>

In Component Initialize isFileUploaded to false , and change isFileUploaded to true in onFileUpload Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM