自定义验证在 Angular 中不起作用

时间:2021-03-03 15:13:36

标签: angular angular-reactive-forms angular-forms

我在 Angular 中有一个带有自定义验证的表单生成器,但是在我的自定义验证中读取文件后,我无法获取该文件的类型。

这是堆栈闪电战:

https://stackblitz.com/edit/angular-ivy-atwqqc?file=src%2Fapp%2Fapp.component.ts

TS 文件

function checkFileType(
  control: AbstractControl
): { [key: string]: any } | null {
  const files: File = control.value;
  const errors: string[] = [];

  if (files) {
    console.log(files);
    if (files.type === "txt") {
      errors.push(`${files[0].name} has an invalid type of unknown\n`);
    }
    console.log(files.type); //This is always null. How can I get file type

    return errors.length >= 1 ? { invalid_type: errors } : null;
  }

  return null;
}


  onSelection($event) {
    const fileReader = new FileReader();
      const file = $event.target.files[0];
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        this.reactiveForm.patchValue({
          file: fileReader.result
        });
      };  
  }

1 个答案:

答案 0 :(得分:1)

问题来自 readAsDataURL()。它将它编码为一个 base 64 字符串,这意味着它没有要查看的属性 type。事实上,它没有任何类型可以查看,因为它是 string 而不是 File。如果您删除它,并将您的 file 变量设置为您的表单,您将获得所需的属性

function checkFileType(
  control: AbstractControl
): { [key: string]: any } | null {
  const file: File = control.value;
  const errors: string[] = [];

  if (file) {
    console.log(file);
    if (file.type === "txt") {
      errors.push(`${file.name} has an invalid type of unknown\n`);
    }
    console.log(file.type); //This is always null. How can I get file type

    return errors.length >= 1 ? { invalid_type: errors } : null;
  }

  return null;
}


  onSelection($event) {
    const fileReader = new FileReader();
      const file = $event.target.files[0];
      fileReader.onload = () => {
        this.reactiveForm.patchValue({
          file: file
        });
      };  
  }
相关问题