0

I have some javascript to validate an image name before upload. It ignores the file path and works correctly on IE and Chrome, but I get an incorrect file alert regardless when using this in firefox or safari.

function validate(elem){
    var alphaExp = /^(?:[\w]\:|\|\\)(\\[a-zA-Z_0-9\-\.]+)+\.(jpg|jpeg|pjpeg|bmp|png|pdf|doc|docx|pub|pubx|id|psd|ai|eps|gif|tiff|zip|rar)$/;
    if(elem.value.match(alphaExp)){
        return true;
    } else{
        alert("File name or type is not suitable! \n\nPlease ensure the file type is one we accept and is named without spaces or special characters.");
        elem.focus();
        return false;
    }
}
NullUserException
  • 83,810
  • 28
  • 209
  • 234
pete
  • 41
  • 1
  • 2
  • 4
  • 1
    It is possible that for security reasons, FF and Safari won't let you access the file's name. Try adding a `console.log(elem.value)` to see exactly what you get. – NullUserException Dec 02 '11 at 22:54
  • 1
    Besides, this is a very poor and Windows-centric way to ignore the file path. – NullUserException Dec 02 '11 at 22:55
  • @NullUserException - Hi, thanks. console.log returns the image. It's also without the file path. Exactly how I want it basically. This is being ignored somewhere along the line else I shouldn't get the alert – pete Dec 02 '11 at 23:26
  • Please give some examples of valid and invalid input strings. e.g. is: `"\\\file.doc"` supposed to be valid? How about: `"|\file.doc"` or just: `"file.doc"`? – ridgerunner Dec 03 '11 at 18:39

1 Answers1

0

Use the change event to trigger the validate function in Firefox and Safari:

document.getElementById("fileUpload").addEventListener("change", validate);

References

Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265