【发布时间】:2022-11-24 14:23:11
【问题描述】:
我正在尝试使用反应式方法验证表单。我正在使用文件输入从用户那里获取文件。我定义了一个自定义验证器,允许用户在特定条件下上传文件。尝试这样做时,出现错误。验证器不会接收整个事件,而只会接收文件的路径,例如 C:\fakepath\abc.xlsx。我想传递 DOM 事件,以便我可以处理文件的所有属性,如类型、大小等。
这是我的代码:
文件.验证器.ts
import { AbstractControl } from '@angular/forms'; export function ValidateFile(control: AbstractControl) : { [key: string]: boolean } | null { const value = control.value; if (!value) { return null; } return value.length < 0 && value.files[0].type !== '.xlsx' && value.files[0].size > 5000000 ? { invalidFile: true } : null; }工作表.component.ts
constructor( private formBuilder: FormBuilder, private alertService: AlertService ) { this.sheetForm = this.formBuilder.group({ sheetType: ['Select Sheet Type', [Validators.required]], sheetUpload: [null, [Validators.required, ValidateFile]], sheetDescription: [ null, [ Validators.required, Validators.minLength(10), Validators.maxLength(100), ], ], }); }工作表.component.html
<div class="input-group"> <label for="sheet-upload">Upload Sheet: </label> <input id="sheet-upload" type="file" (change)="handleFileInput($event)" formControlName="sheetUpload" accept=".xlsx" /> <small id="custom-error-message" *ngIf=" (sheetForm.get('sheetUpload').dirty || sheetForm.get('sheetUpload').touched) && sheetForm.get('sheetUpload').invalid " > The file size exceeds 5 MB or isn't a valid excel type. Please upload again. </small> </div>任何帮助,将不胜感激。谢谢!
【问题讨论】:
标签: javascript angular typescript