简体   繁体   中英

Multiple file extension validation using Angular

I'm trying to validate the file type for multiple file uploads but it says "errors" not found. Please let me know if I'm way off and if so what would be a better way to check file type for multiple files. Thank you!

test-data.component.ts


testDataFileType = "doc,docx,xls,xlsx,pdf,application/msword,application/msexcel,application/pdf";


tdmForm=this.fb.group({
requirement:this.fb.array([this.fb.control('', [Validators.required, fileExtensionValidator(this.testDataFileType)])])
});

constructor(public fb: FormBuilder,){}

file-extension-validator.directive.ts


export function fileExtensionValidator(validExt: string): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
      let forbidden = true;
      if (control.value) {
        const fileExt = control.value.split('.').pop();
        validExt.split(',').forEach(ext => {
          if (ext.trim() == fileExt) {
            forbidden = false;
          }
        });
      }
      return forbidden ? { 'inValidExt': true } : null;
    };
  } 

test-data.component.html

     <file-upload [acceptedFileType]="testDataFileType" imagePath="upload_files.png" 
      typeOfFile="requirement"[files]="requirement"></file-upload>
      <div *ngIf="isFormSubmitted && this.requirement.length == 0" class="text-error">
        <ng-container>You must upload a file.</ng-container>
      </div>
      <div *ngFor="let f of this.requirement; index as i">
      <div *ngIf="this.requirement[i].errors?.inValidExt">Invalid file type.</div>
    </div>

If the problem is in the HTML Template; I do see a few possibilities.

First, you are looping over this.requirement with the *ngFor . Inside the loop you can access the index variable, instead of this.requirement a second time.

Second, the error tells you exactly what the problem is. The errors variable does not existe on at least one of the objects in the this.requirement array. You can probably get around this by adding another safe navigation operator--like you already are doing on the errors object.

Try this as the last few lines of your HTML Template file:

<div *ngFor="let f of this.requirement; index as i">
  <div *ngIf="f?.errors?.inValidExt">Invalid file type.</div>
</div>

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