Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload validation by JavaScript

Tags:

javascript

I want to restrict a file upload control to allow PDF files only. I want to use JavaScript for that.

I want to apply that JavaScript in file upload event.

like image 326
gbbosmiya Avatar asked May 03 '26 16:05

gbbosmiya


2 Answers

You can check the file name on submit.

"hook to the <form>'s onsubmit with whatever method" {
  filename = theFileElement.value;
  if (!/\.pdf$/i.test(filename)) {
    alert("error");
    return false;
  }
  return true;
}

Note that this only checks if the file has an extension of .pdf. It does not (and cannot) check whether the file is really a just PDF or actually a nasty virus. Moreover, client side Javascript can easily be bypassed, so you should perform the check again on the server side.

like image 98
kennytm Avatar answered May 05 '26 07:05

kennytm


var ext = fname.split(".");
var x=ext.length;
if(ext[x-1] == 'pdf'){
  alert("Please upload doc file");
  document.form.fname.focus();
  return false;
}
like image 31
sivaraman Avatar answered May 05 '26 07:05

sivaraman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!