在Angular 4中对<input type="file">
使用验证,可以通过以下步骤实现:
文件输入验证通常涉及检查文件的类型、大小和其他属性,以确保用户上传的文件符合应用程序的要求。
以下是一个简单的示例,展示如何在Angular 4中对文件输入进行类型和大小的验证:
<form [formGroup]="fileUploadForm" (ngSubmit)="onSubmit()">
<input type="file" formControlName="file" (change)="onFileChange($event)" />
<div *ngIf="fileUploadForm.controls['file'].invalid && (fileUploadForm.controls['file'].dirty || fileUploadForm.controls['file'].touched)">
<div *ngIf="fileUploadForm.controls['file'].errors.required">
File is required.
</div>
<div *ngIf="fileUploadForm.controls['file'].errors.invalidFileType">
Invalid file type. Allowed types: {{ allowedFileTypes.join(', ') }}.
</div>
<div *ngIf="fileUploadForm.controls['file'].errors.invalidFileSize">
File size exceeds the limit of {{ maxFileSize }}MB.
</div>
</div>
<button type="submit" [disabled]="fileUploadForm.invalid">Submit</button>
</form>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
fileUploadForm: FormGroup;
allowedFileTypes = ['image/jpeg', 'image/png'];
maxFileSize = 5; // in MB
constructor(private fb: FormBuilder) {
this.fileUploadForm = this.fb.group({
file: ['', [Validators.required, this.fileTypeValidator.bind(this), this.fileSizeValidator.bind(this)]]
});
}
onFileChange(event) {
const file = event.target.files[0];
if (file) {
this.fileUploadForm.get('file').setValue(file);
}
}
fileTypeValidator(control) {
const file = control.value;
if (file) {
return this.allowedFileTypes.includes(file.type) ? null : { invalidFileType: true };
}
return null;
}
fileSizeValidator(control) {
const file = control.value;
if (file) {
const sizeInMB = file.size / (1024 * 1024);
return sizeInMB <= this.maxFileSize ? null : { invalidFileSize: true };
}
return null;
}
onSubmit() {
if (this.fileUploadForm.valid) {
console.log('Form submitted with valid file:', this.fileUploadForm.value.file);
// Proceed with file upload logic here
}
}
}
如果在实现过程中遇到问题,如验证不生效或错误信息不正确,可以检查以下几点:
formControlName
是否正确设置。*ngIf
条件是否正确反映了表单控件的状态。通过以上步骤,可以在Angular 4中有效地实现对文件输入的验证。
领取专属 10元无门槛券
手把手带您无忧上云