【问题标题】:how to validate file control on file upload on angular 5如何在 Angular 5 中验证文件上传的文件控制
【发布时间】:2018-04-27 18:43:14
【问题描述】:

我正在尝试学习 Angular 5。在创建表单中有一个文件字段

<input type="file" class="form-control-file" formControlName = "fileInput" fileInput >
<div *ngIf="angForm.controls.fileInput.sizeinvalid && (angForm.controls.fileInput.dirty || angForm.controls.fileInput.touched)" class="alert alert-danger">
    <div *ngIf="angForm.controls.fileInput.errors.invalid">Maximum allowed image Size is 5 MB</div>
</div>

我创建了一个 customValidator 类并在模块中注册。为了启动更改验证器,我添加了@HostListener

@Directive({
   selector: "[fileInput]",
   providers: [
    { provide: NG_VALIDATORS, useExisting: FileValidator, multi: true },
  ]
})
export class FileValidator implements Validator {
   constructor(private el: ElementRef) { }
   @HostListener('change', ['$event.target']) onChange(target) {
       this.validate(this.el.nativeElement);      
   }

   static validate(c: FormControl): {[key: string]: any} {
      if (c.size > 0) {
         console.log("Maximum size")
         return { "sizeinvalid" : true};
      } else {
         console.log('No size');
         return null;
      }       
   }

   validate(c: FormControl): {[key: string]: any} {
      return FileValidator.validate(c);
   }
}

但是,代码没有给我任何验证错误。请找出需要的更正。

【问题讨论】:

    标签: angular


    【解决方案1】:

    我已通过为文件控件添加 registerOnChange 解决了该解决方案。请查看link,找到我选择的解决方案。

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 1970-01-01
      • 2019-01-19
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2021-05-23
      相关资源
      最近更新 更多