JavaScript file validation validation

I want to limit file upload control to allow only PDF files. I want to use JavaScript for this.

I want to apply this JavaScript in a file upload event.

+3
source share
2 answers

You can check the file name to send.

"hook to the <form> 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 .pdf. It does not (and cannot) check whether the file is really just a PDF or actually a nasty virus. In addition, client-side Javascript can be easily circumvented, so you must run server-side validation again.

+5
source
var ext = fname.split(".");
var x=ext.length;
if(ext[x-1] == 'pdf'){
  alert("Please upload doc file");
  document.form.fname.focus();
  return false;
}
+1
source

Source: https://habr.com/ru/post/1747666/


All Articles