Posted By

MMDeveloper on 12/29/09


Tagged

prototype


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tuffstudio


Extract and Validate Filename and Extension from file form field


 / Published in: JavaScript
 

URL: http://skyward.nefec.org

This assumes a file field in a form with an id of "fileField", and the usage of the prototype library. Here you can use javascript as a first tier of security on restricting what kind of files may be uploaded with your form.

  1. function extractFileName (string) {
  2. if (string.indexOf('/') > -1) {
  3. fileName = string.substring(string.lastIndexOf('/') + 1, string.length);
  4. }
  5. else {
  6. fileName = string.substring(string.lastIndexOf('\\') + 1, string.length);
  7. }
  8.  
  9. return fileName;
  10. }
  11.  
  12. var fileField = $("fileField");
  13. var fileName = extractFileName(fileField.value).replace(/^\s|\s$/g, "");
  14.  
  15. if (fileName.match(/([^\/\\]+)\.(gif|jpg|bmp|png|pjpeg)$/i) || fileName.blank() === true) {
  16. //good file
  17. }
  18. else {
  19. alert("I currently only accept the following file formats for the screenshot field: gif, jpg, bmp, png, pjpeg.");
  20. }

Report this snippet  

You need to login to post a comment.