I have a upload attachment in react spfx , need to validate file based on the type, it should only allow pdf files other extensions should trigger an alert. I have added accept =".pdf" in input of the file, it does filter the extension to pdf but if the user changes it, it still accepts other file type, how to add validation to check the extension type before form submit? below is the attachment file code.
<Label ><h3><b>Please upload PDF files only</b></h3></Label>
<input type="file" accept=".pdf" name="file-1[]" id="file-1" hidden
multiple
onChange={(e) => this.OnfileChange(e)}
/>
<Label required htmlFor="file-1" className={styles.fileBrowse}><FaUpload />
<span> Upload Attachment</span></Label>
</div>
</div>}
<div className={styles.row}>
<ul className="DocsData">
{this.state.uploadedDocsList.map(colorItem => {
return (<li className="listStyle">
<a href={colorItem.ServerRelativeUrl} target="_blank" data-interception="off" className={styles.docslinK}>
<FileTypeIcon type={IconType.image} path={colorItem.ServerRelativeUrl} />
{colorItem.FileName}</a>
<button hidden={this.state.FormType == "DISP"} className="deleteButton btn-danger"
onClick={() => this.OnDocsDelete(colorItem.FileName)}
style={{ margin: "2px 6px", "border": 0 }} >X</button></li>);
})}
</ul>
</div>
</div> ```
``` /* this method to for uploading select files to collection object */
private UploadFiles() {
// totDocsFiles = [];
uploadedDocsList = this.state.uploadedDocsList;
for (var Count = 0; Count < files.length; Count++) {
var file = files[Count];
var FileName = files[Count].name;
let filterCheck = this.state.uploadedDocsList.filter((element) => {
if (FileName == element.FileName) {
return element;
}
});
if (filterCheck.length == 0) {
uploadedDocsList.push({
'FileName': FileName,
'ServerRelativeUrl': '#'
});
totDocsFiles.push({
name: FileName,
content: file
});
}
}
this.setState({ uploadedDocsList: uploadedDocsList });
}
/* this method to handle document delete on file upload controle */
private OnDocsDelete(docName) {
let totDocsFilesTemp: string[] = [];
uploadedDocsList = this.state.uploadedDocsList.filter((enteringItem) => {
if (enteringItem.FileName != docName) {
return enteringItem;
}
else {
if (enteringItem.ServerRelativeUrl != "#") {
docstoDelete.push(enteringItem.FileName);
}
else {
totDocsFilesTemp = totDocsFiles.filter((totDocsFile) => {
if (totDocsFile.name != docName) {
return totDocsFile;
}
});
totDocsFiles = totDocsFilesTemp;
}
}
});
this.setState({ uploadedDocsList: uploadedDocsList });
}
private onFormatDate(date?: Date): string {
return !date ? '' : moment(date.toISOString()).format('MM/DD/YYYY');
} ```

