I'm currently working on validating a form using the reactive approach. I've implemented a file input to allow users to upload files, with custom validation conditions in place. However, I'm encountering an issue where the validator only receives the file path (e.g., C:\fakepath\abc.xlsx
) instead of the full event object. I need access to all file properties like type and size within the validator function.
Here's the relevant code snippet:
file.validator.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;
}
sheet.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),
],
],
});
}
sheet.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>
Any advice or guidance would be highly appreciated. Thank you!